我需要知道当前页面的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;
}
}
我使用了Blazor存储库的NavLink组件中使用的相同方法,但它不起作用。有什么好主意吗?
发布于 2018-04-30 23:43:42
连接到页面或组件中的OnLocationChanged
事件没有任何用处,因为它们是按需加载和处理的。
您应该在app.cshtml中注册此事件,因为它不会被释放。
发布于 2018-05-29 08:50:59
您应该监听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);
}
}
}
https://stackoverflow.com/questions/50102726
复制相似问题