Blazor 导航管理器取消位置已更改的导航

问题描述 投票:0回答:4

问题:

Blazor 上有取消导航的方法吗?

让我们假设一个简单的

a href
,如下所示:

<a href="/some/other/blazor/spa/page">Go</a>

我想取消导航(例如,如果我们正在编辑表单)

我已经尝试过了。

通过JS

我通过 JSInterop 设置

onbeforeunload
dom 委托:

window.onbeforeunload = function(){
        return 'Vols abandonar aquesta pàgina?';
      };

但 Blazor 绕过了它。

途径地点已更改

我尝试拦截

locationchanged
事件上的导航,但没有成功:

@implements IDisposable
@inject NavigationManager NavigationManager

...

protected override void OnInitialized()
{
    NavigationManager.LocationChanged += HandleLocationChanged;
}

private void HandleLocationChanged(object sender, LocationChangedEventArgs e)
{
    // Cancel Navigation Here
}

public void Dispose()
{
    NavigationManager.LocationChanged -= HandleLocationChanged;
}
c# .net-core navigation blazor blazor-webassembly
4个回答
5
投票

此功能是在 .NET 7 中添加的,可以在“路由和导航”页面的“处理/防止位置更改”部分找到文档。 该文档中的以下示例显示了处理导航开始的代码(在

OnLocationChanging

方法中),然后在用户尝试导航到计数器页面时取消该导航。


NavigationManager Navigation <p> <button @onclick="@(() => Navigation.NavigateTo("/"))"> Home (Allowed) </button> <button @onclick="@(() => Navigation.NavigateTo("/counter"))"> Counter (Prevented) </button> </p> @code { private IDisposable? registration; protected override void OnAfterRender(bool firstRender) { if (firstRender) { registration = Navigation.RegisterLocationChangingHandler(OnLocationChanging); } } private ValueTask OnLocationChanging(LocationChangingContext context) { if (context.TargetLocation == "/counter") { context.PreventNavigation(); } return ValueTask.CompletedTask; } public void Dispose() => registration?.Dispose(); } ```
    

5
投票
https://github.com/dotnet/aspnetcore/pull/24417

在 Blazor 中导航时页面不会更改,因此没有卸载来触发 onbeforeunload。


1
投票

截至 2021 年 5 月 17 日,

NavigationManger

的地点变更活动现已承诺针对

.NET 6.0
。我希望能够在应用程序中捕捉到全球范围内的这一事件。

https://github.com/dotnet/aspnetcore/issues/14962


-2
投票

© www.soinside.com 2019 - 2024. All rights reserved.