繁体   English   中英

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

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

我在我的应用程序中使用 URL 参数作为页面状态。

如何在不实际导航的情况下更改 URL?

谢谢!

(使用 blazor 服务器端)

您可以使用 JS Interop 执行此操作并调用history.pushState(null, '', url)

这是一个简单的例子

。剃刀

@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

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

请注意,这仅适用于视觉目的,它只会在服务器端为浏览器更改,您可能不会看到更改。

如果您只想在 URL 中添加/删除/更改查询参数,请使用NavigationManager.NavigateTo方法。 如果不需要(或未使用forceReload标志调用),它将不会重新加载页面。

比如当前的 URL 是"https://example.com/page" ,那么调用NavigationManager.NavigateTo("https://example.com/page?id=1")不会重新加载页面,只会修改 URL . 单击浏览器中的“返回”会将 URL 更改为"https://example.com/page" ,此更改可以通过NavigationManager.LocationChanged事件处理。

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