我需要知道当前页面的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, string newUriAbsolute)
{
url = newUriAbsolute;
}
public void Dispose()
{
UriHelper.OnLocationChanged -= OnLocationChanged;
}
}
我使用了与Blazor存储库中的NavLink组件相同的方法,但它没有用。有任何想法吗?。
简而言之,使用来自IUriHelper的GetAbsoluteUri():
1)不要忘记在.cshtml
注射UriHelper:
@inject Microsoft.AspNetCore.Components.Services.IUriHelper UriHelper
//for <= 0.7.0 versions use:
//@inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper
或者在基类继承中为“代码隐藏”体验.cs
:
[Inject]
public Microsoft.AspNetCore.Components.Services.IUriHelper UriHelper {get; set;}
//for <= 0.7.0 versions use:
//[Inject]
//public Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper {get; set;}
2)调用GetAbsoluteUri
方法:
string currentUrl = UriHelper.GetAbsoluteUri()
编辑On 0.8.0, IUriHelper
has moved to Microsoft.AspNetCore.Components.Services
namespace。
在页面或组件中连接OnLocationChanged
事件没有用处,因为它们被加载并处理在demannd上。
您应该在app.cshtml中注册此事件,因为这不会被处理。
你应该听一下IUriHelper的LocationChange,它触发函数做你想做的事情,例如:
@using Microsoft.AspNetCore.Blazor.Components
@using Microsoft.Extensions.Logging
@inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper
@inject ILogger<NavItem> logger
<li class="m-menu__item @(Active ? "m-menu__item--active" : "")">
<a href=@Url class="m-menu__link ">
<span class="m-menu__item-here"></span>
<i class="m-menu__link-icon @Icon"></i>
<span class="m-menu__link-text">@Text</span>
</a>
</li>
@functions {
protected override void OnInit()
{
UriHelper.OnLocationChanged += OnLocationChanges;
}
[Parameter]
private string Url { get; set; }
[Parameter]
private string Icon { get; set; }
[Parameter]
private string Text { get; set; }
private bool Active = false;
private void OnLocationChanges(object sender, string newLocation)
{
bool active = newLocation.Contains(Url);
if(active != Active) //Only re-render the components that need it
{
Active = active;
StateHasChanged();
logger.LogInformation("Location Change To:" + newLocation);
}
}
}