简体   繁体   English

Blazor 导航:在不更改重新加载页面的情况下更新 URL

[英]Blazor Navigation: Update URL without changing reloading page

I use URL parameters for page state in my app.我在我的应用程序中使用 URL 参数作为页面状态。

How can i change the URL without actually navigating?如何在不实际导航的情况下更改 URL?

Thanks!谢谢!

(using blazor server side) (使用 blazor 服务器端)

You can do this with JS Interop and call history.pushState(null, '', url)您可以使用 JS Interop 执行此操作并调用history.pushState(null, '', url)

Here is a simple example这是一个简单的例子

.razor 。剃刀

@page "/"
@inject IJSRuntime jsRuntime

<input
    @bind="url"
/>

<button @onclick="ChangeUrl">
    Change Url
</button>

<p>@url</p>

@code {
    [Parameter]
    public string Url { get; set; }

    void ChangeUrl(){
        // You can also change it to any url you want
        jsRuntime.InvokeVoidAsync("ChangeUrl", Url);
    }
}

.js .js

window.ChangeUrl = function(url){
    history.pushState(null, '', url);   
}

Please notice that this only works for visual purpose, it will only change for the browser while in the server side, you probably won't see the change.请注意,这仅适用于视觉目的,它只会在服务器端为浏览器更改,您可能不会看到更改。

If you just want to add/remove/change query parameters in the URL, use the NavigationManager.NavigateTo method.如果您只想在 URL 中添加/删除/更改查询参数,请使用NavigationManager.NavigateTo方法。 It will not reload the page if it is not necessary (or not called with forceReload flag).如果不需要(或未使用forceReload标志调用),它将不会重新加载页面。

For example, the current URL is "https://example.com/page" , then call NavigationManager.NavigateTo("https://example.com/page?id=1") will not reload the page but only modify URL.比如当前的 URL 是"https://example.com/page" ,那么调用NavigationManager.NavigateTo("https://example.com/page?id=1")不会重新加载页面,只会修改 URL . Click "Back" in browser will change the URL to "https://example.com/page" , this change can be handled with NavigationManager.LocationChanged event.单击浏览器中的“返回”会将 URL 更改为"https://example.com/page" ,此更改可以通过NavigationManager.LocationChanged事件处理。

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.navigationmanager.navigateto https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.navigationmanager.navigateto

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM