在Blazor WebAssembly中使用LocalStorage时,有时候会遇到一些JSInterop错误。以下是一种可能的解决方法:
在wwwroot
目录下创建一个名为interop.js
的新文件,并添加以下代码:
window.localStorageFunctions = {
setItem: function(key, value) {
localStorage.setItem(key, value);
},
getItem: function(key) {
return localStorage.getItem(key);
},
removeItem: function(key) {
localStorage.removeItem(key);
}
};
index.html
文件中引入interop.js
:
Blazor WebAssembly
Loading...
using Microsoft.JSInterop;
using System.Threading.Tasks;
public class LocalStorageService
{
private readonly IJSRuntime _jsRuntime;
public LocalStorageService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public async Task SetItem(string key, string value)
{
await _jsRuntime.InvokeVoidAsync("localStorageFunctions.setItem", key, value);
}
public async Task GetItem(string key)
{
return await _jsRuntime.InvokeAsync("localStorageFunctions.getItem", key);
}
public async Task RemoveItem(string key)
{
await _jsRuntime.InvokeVoidAsync("localStorageFunctions.removeItem", key);
}
}
@inject LocalStorageService localStorage
@code {
private string value;
protected override async Task OnInitializedAsync()
{
value = await localStorage.GetItem("key");
}
private async Task SaveValue()
{
await localStorage.SetItem("key", value);
}
}
这样,你就可以在Blazor WebAssembly中使用LocalStorage了,并且解决了可能出现的JSInterop错误。