我需要动态更新web程序集中的侧导航栏。
你能建议我怎么做吗?
@page "/ChildPage"
@code{
public List<string> menus = new List<string>();
NavMenu n = new NavMenu();
protected override async Task OnInitializedAsync()
{
menus.Add("Content 1");
menus.Add("Content 2");
await Task.Run(() => n.MenuItems = menus);
}
}
在导航菜单中,剃须刀做了如下操作。
<div class="@NavMenuCssClass" @onclick="ToggleNavMenu">
<ul class="nav flex-column">
@if (MenuItems != null)
{
@foreach (var menu in MenuItems)
{
<li class="nav-item px-3">
<NavLink class="nav-link" href="Page1">
<span class="oi oi-plus" aria-hidden="true"></span> @menu
</NavLink>
</li>
}
}
</ul>
</div>
@code {
private bool collapseNavMenu = true;
private string NavMenuCssClass => collapseNavMenu ? "collapse" : null;
private void ToggleNavMenu()
{
collapseNavMenu = !collapseNavMenu;
}
public List<string> MenuItems = new List<string>() { "Page 1", "Page 2"};
}
你能建议我如何从每个页面更新导航栏吗。
您可以创建这样的服务
public interface IMenuService
{
List<MenuItem> AdditionalMenuItems { get; set; }
event EventHandler<EventArgs> OnChanged;
void NotifyChanged();
}
将其注册为作用域
services.AddScoped<IMenuService, MenuService>();
你可以将其注入你的页面并添加
@inject IMenuService MenuService
protected override void OnInitialized()
{
MenuService.Add(whatever);
MenuService.NotifyChanged();
}
在您的布局
@implements IDisposable
@inject IMenuService MenuService
@foreach(MenuItem menuItem in MenuService.AdditionalMenuItems)
{
// Whatever
}
// code section
protected override void OnInitialized()
{
MenuService.OnChanged += MenuChanged;
}
void IDisposable.Dispose()
{
MenuService.OnChanged -= MenuChanged;
}
private void MenuChanged(EventArgs e)
{
InvokeAsync(StateHasChanged);
}