要在Blazor WebAssembly应用程序中实现此功能,您可以使用C#中的OnBeforeUnload事件,该事件会在用户尝试离开具有未保存更改的网页时触发。
下面是一个示例组件,它将响应OnBeforeUnload事件并提示用户在离开具有未保存更改的网页之前保存更改:
@page "/example"
@implements IDisposable
@inject IJSRuntime jsRuntime
Example Page
Unsaved Changes: @unsavedChanges
@code {
private bool unsavedChanges = false;
private bool hasNavigated = false;
protected override void OnInitialized()
{
jsRuntime.InvokeVoidAsync("window.addEventListener", "beforeunload", new DotNetObjectRef(this, jsRuntime));
}
[JSInvokable]
public void OnBeforeUnload()
{
if (unsavedChanges && !hasNavigated)
{
jsRuntime.InvokeVoidAsync("confirm", "You have unsaved changes. Are you sure you want to leave this page?");
}
}
protected override void OnNavigating(NavigationEventArgs args)
{
if (unsavedChanges && !hasNavigated && !args.Cancel)
{
args.Cancel = true;
jsRuntime.InvokeVoidAsync("confirm", "You have unsaved changes. Are you sure you want to navigate away from this page?");
}
else
{
hasNavigated = true;
}
}
private void SaveChanges()
{
// Save changes logic here
unsavedChanges = false;
}
private void UnsavedChangesDetected()
{
unsavedChanges = true;
}
public void Dispose()
{
jsRuntime.InvokeVoidAsync("window.removeEventListener", "beforeunload", new DotNetObjectRef(this, jsRuntime));
}
}
这个示例组件演示了如何在Blazor WebAssembly应用程序中使用OnBeforeUnload事件来提示用户保存未保存的更改。在OnBeforeUnload方法中,如果有未保存的更改并且用户尚未导航到另一个页面,则会弹出确认对话框。在OnNavigating方法中,如果有未保存的更改并且用户尚未导航到另一页,则会取消导航并弹出确认对话框。
此解决方法