Can the state of the Counter in the example Blazor project be preserved between page switches?

前端 未结 4 934
情书的邮戳
情书的邮戳 2021-01-15 21:37

In the default example project for both server-side Blazor and WebAssembly Blazor projects, the Counter example resets to 0 every time you move between the pages. However, o

4条回答
  •  借酒劲吻你
    2021-01-15 22:23

    It looks like this exact scenario is discussed in https://docs.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-3.0#client-side-in-the-browser

    Seems Blazor just doesn't handle it out-of-the-box, but you just need to use localStorage or sessionStorage.

    Using the Blazor.Extensions.Storage NuGet package (https://github.com/BlazorExtensions/Storage):

    @page "/counter"
    
    @inject ISessionStorage SessionStorage
    @using Blazor.Extensions.Storage.Interfaces
    
    

    Counter

    Current count: @currentCount

    @code { private int currentCount = 0; protected override async Task OnInitializedAsync() { currentCount = await SessionStorage.GetItem("counter"); } private async void IncrementCount() { currentCount++; await SessionStorage.SetItem("counter", currentCount); } }

提交回复
热议问题