67

我需要知道当前页面的 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 组件中使用的相同方法,但它不起作用。有任何想法吗?。

4

3 回答 3

151

使用类中的Uri属性NavigationManager

这个怎么运作

在页面上使用它之前从注入中获取它.razor

@inject NavigationManager MyNavigationManager

或者.cs如果您更喜欢“代码隐藏”体验,可以在文件中这样:

using Microsoft.AspNetCore.Components;
...
[Inject]
public NavigationManager MyNavigationManager {get; set;}

样本

@page "/navigate"
@inject NavigationManager MyNavigationManager

<h1>Current URL</h1>

<p>@(MyNavigationManager.Uri)</p>

有关导航(NavigateTo、BaseUri、ToAbsoluteUri、ToBaseRelativePath、...)的更多信息,请参见:URI 和导航状态助手

NavigationManager 备忘单

MyNavigationManager.Uri
#> https://localhost:5001/counter/3?q=hi

MyNavigationManager.BaseUri
#> https://localhost:5001/

MyNavigationManager.NavigateTo("http://new location")
#> Navigates to new location

MyNavigationManager.LocationChanged
#> An event that fires when the navigation location has changed.

MyNavigationManager.ToAbsoluteUri("pepe")
#> https://localhost:5001/pepe

MyNavigationManager.ToBaseRelativePath(MyNavigationManager.Uri)
#> counter/3?q=hi

Helper: AddQueryParm( "q2", "bye" ) // (*1)
#> https://localhost:5001/counter/3?q=hi&q2=bye

Helper: GetQueryParm( "q" )
#> hi

(*1)Net6 介绍GetUriWithQueryParameter。更多信息:从 Blazor 操作查询字符串

助手代码:

@code {

    [Parameter]
    public string Id { get; set; }

    // Blazor: add parm to URL
    string AddQueryParm(string parmName, string parmValue)
    {
        var uriBuilder = new UriBuilder(MyNavigationManager.Uri);
        var q = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);
        q[parmName] = parmValue;
        uriBuilder.Query = q.ToString();
        var newUrl = uriBuilder.ToString();
        return newUrl;
    }

    // Blazor: get query parm from the URL
    string GetQueryParm(string parmName)
    {
        var uriBuilder = new UriBuilder(MyNavigationManager.Uri);
        var q = System.Web.HttpUtility.ParseQueryString(uriBuilder.Query);
        return q[parmName] ?? "";
    }

}
于 2018-11-23T14:15:00.643 回答
3

连接到页面或组件中的事件是没有用的OnLocationChanged,因为它们是按需加载和处理的。

您应该在 app.cshtml 中注册此事件,因为它不会被释放。

于 2018-04-30T15:43:41.523 回答
1

您应该听 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);
        }
    }
}
于 2018-05-29T00:50:58.770 回答