我需要知道当前页面的 URL,以便检查是否需要对元素应用某种样式。下面的代码就是一个例子。
@using Microsoft.AspNetCore.Blazor.Services
@inject IUriHelper UriHelper
@implements IDisposable
<h1>@url</h1>
<nav>
<div class="nav-wrapper">
<a href="#" class="brand-logo">Blazor</a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li>
<NavLink href="/" Match=NavLinkMatch.All>
Home
</NavLink>
</li>
<li>
<NavLink href="/counter">
Counter
</NavLink>
</li>
<li>
<NavLink href="/fetchdata">
Fetch data
</NavLink>
</li>
</ul>
</div>
</nav>
@functions {
private string url = string.Empty;
protected override void OnInit()
{
url = UriHelper.GetAbsoluteUri();
UriHelper.OnLocationChanged += OnLocationChanged;
}
private void OnLocationChanged(object sender, LocationChangedEventArgs e)
{
url = newUriAbsolute;
}
public void Dispose()
{
UriHelper.OnLocationChanged -= OnLocationChanged;
}
}
I used the same approach used in the NavLink component in the Blazor repository, but it did not work. Any ideas?.