我在左側導航中有一個選單,它將根據 isAdmin 條件隱藏/顯示。我在 Index.Razor 頁面上獲得了 isAdmin 的值。現在,如果 isAdmin 為真,我想重新渲染左側導航,下面的導航項應該是可見的
@if (isAdmin)
{
<a class="nav-items" target="_blank">
<div style="width:40px;">
<i title="Security" class="fab fa-expeditedssl fa-fw" style="color: white; font-size: 30px;"></i>
</div>
<span class="nav-items-text" style="color:white; visibility:@Visibility">Security</span>
</a>
}
更改 Blazor 選單中導航項的可見性
正如上面的鏈接所建議的,我在服務中創建了 AppStateService。下面是我的 AppStateService 代碼
public class AppStateService
{
private bool isAdmin;
public event Action OnChange;
public bool IsAdmin
{
get { return isAdmin; }
set
{
if (isAdmin != value)
{
isAdmin = value;
NotifyStateChanged();
}
}
}
private void NotifyStateChanged() => OnChange?.Invoke();
}
在索引頁面上,我使用并分配了
@inject AppStateService AppStateService
AppStateService.IsAdmin = true;
在左側導航組件上,我使用了
@inject AppStateService AppStateService
@implements IDisposable
左側導航組件
protected override async Task OnInitializedAsync()
{
AppStateService.OnChange = StateHasChanged;
}
public void Dispose()
{
AppStateService.OnChange -= StateHasChanged;
}
也添加在 Startup 類中。
但是現在我將如何在左側導航中獲取 isAdmin 的值,從 Index.Razor 頁面顯示/隱藏導航項。
uj5u.com熱心網友回復:
您的導航條碼:
protected override void OnInitialized()
=> appStateService.OnChange = OnAppStateChanged;
private void OnAppStateChanged()
=> InvokeAsync(StateHasChanged);
public void Dispose()
=> appStateService.OnChange -= OnAppStateChanged;
和一個測驗頁:
@page "/"
@inject AppStateService appStateService;
<PageTitle>Index</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
@code{
protected async override Task OnInitializedAsync()
{
this.appStateService.IsAdmin = false;
await this.GetIsAdmin();
}
private async ValueTask GetIsAdmin()
{
//emulate an async API call
await Task.Delay(500);
var isAdmin = (Random.Shared.Next(0, 2)) == 0;
this.appStateService.IsAdmin = isAdmin;
}
}
uj5u.com熱心網友回復:
我認為您的方法是正確的,但請嘗試將代碼添加到索引頁面而不是導航組件中。
索引頁面
@inject AppStateService AppStateService
@implements IDisposable
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
AppStateService.IsAdmin = true;
AppStateService.OnChange = StateHasChanged;
}
}
public void Dispose()
{
AppStateService.OnChange -= StateHasChanged;
}
導航組件,保持不變。
@if (AppStateService.IsAdmin)
{
<a class="nav-items" target="_blank">
<div style="width:40px;">
<i title="Security" class="fab fa-expeditedssl fa-fw" style="color: white; font-size: 30px;"></i>
</div>
<span class="nav-items-text" style="color:white; visibility:@Visibility">Security</span>
</a>
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/497174.html
