在以前的版本(.NET 7)中,我使用 NavigationLock 组件没有遇到任何问题。但是,升级到 .NET 8 后,我遇到了一个问题:NavigationLock 似乎没有触发任何事件。为了解决这个问题,我使用标准模板页面创建了一个新项目并实施了
我像往常一样导航锁定。尽管如此,预期的事件并未被激活。
这是代码:
@page "/counter"
@rendermode InteractiveServer
@inject IJSRuntime js
<PageTitle>Counter</PageTitle>
<NavigationLock OnBeforeInternalNavigation=this.OnNavigationAway ConfirmExternalNavigation></NavigationLock>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
async Task OnNavigationAway(LocationChangingContext context)
{
var confirmed = await ShowConfirmationDialogAsync();
if (!confirmed)
{
context.PreventNavigation();
}
}
private async Task<bool> ShowConfirmationDialogAsync()
{
var s = await js.InvokeAsync<bool>("confirm", "Caught this navigation event! Do you want to continue?");
return s;
}
}
你能帮我吗? 预先感谢。
我用您的代码在我这边重现了您的问题。在.net 7 blazor服务器中,当我单击导航菜单从Counter页面转到索引时,或者单击我在Counter组件中添加的
<a href="/">jump to index page</a>
时,两者都会触发导航事件,我会得到js提示。但在 .net 8 Web 应用程序 SSR 计数器组件中,只有当我使用像 官方示例显示的那样的
Navigation.NavigateTo("/");
时,这两个操作都不会触发事件。
所以恐怕我们只能通过注册
RegisterLocationChangingHandler
来编写自定义逻辑,就像 NavMenu 组件中显示的示例一样。