Blazor Webassembly多标签页实现非iframe的实现

前面用iframe实现了多标签页,这次是不用iframe实现的多标签页.参考了一下Ant Design Blazor.
基本功能已经都实现了不论是标签滚动、激活、左移、右移、关闭其他,还是在内容页跳转、新增、关闭标签都有实现。
已经可以用来做实际项目
源码地址: https://github.com/liningit/BlazorWebassemblyMultiPagesTabNoIframe
实现原理是新建一个类继承RouteView,在此类里面的Render方法中可以通过RouteData获取当前路由对应的对象.然后生成RenderFragment.
然后将其保存到List中,然后循环显示出来.对于未激活的通过display:none隐藏就可以了,这样哪怕切换标签状态也是保存的并不会刷新

    public class ReuseTabsRouteView : RouteView
    {
        [Inject]
        public TabSetTool TabSetTool { get; set; }

        [Inject]
        public NavigationManager Navmgr { get; set; }
         
        protected override void Render(RenderTreeBuilder builder)
        {
            var layoutType = RouteData.PageType.GetCustomAttribute<LayoutAttribute>()?.LayoutType ?? DefaultLayout;

            var body = CreateBody(RouteData, Navmgr.Uri);

            builder.OpenComponent<CascadingValue<ReuseTabsRouteView>>(0);
            builder.AddAttribute(1, "Name", "RouteView");
            builder.AddAttribute(2, "Value", this);

            builder.AddAttribute(3, "ChildContent", (RenderFragment)(b =>
            {
                b.OpenComponent(20, layoutType);
                b.AddAttribute(21, "Body", body);
                b.CloseComponent();
            }));

            builder.CloseComponent();
            var url = "/" + Navmgr.ToBaseRelativePath(Navmgr.Uri);
            if (url != "/#")
            {
                var selTab = TabSetTool.Pages.FirstOrDefault(m => m.Url == url && (m.Title == TabSetTool.Title || string.IsNullOrEmpty(m.Title)));
                if (selTab == null)
                {
                    TabSetTool.Pages.Add(new Tab
                    {
                        Body = body,
                        Url = url,
                        Title = TabSetTool.Title,
                        IsActive = true,
                    });
                }
                else
                {
                    selTab.Title = TabSetTool.Title;
                    selTab.Body = body;
                    selTab.IsActive = true;
                }
            }
        }

        private RenderFragment CreateBody(RouteData routeData, string url)
        {
            return builder =>
            {
                builder.OpenComponent(0, routeData.PageType);
                foreach (var routeValue in routeData.RouteValues)
                {
                    builder.AddAttribute(1, routeValue.Key, routeValue.Value);
                }
                builder.CloseComponent();
            };
        }


    }

App.razor中将RouteView改成ReuseTabsRouteView.

另外要注意TabSet中一定要有

[CascadingParameter(Name = "RouteView")]
public ReuseTabsRouteView RouteView { get; set; }

这两句,要不然页面会不更新

上一篇:Spring Boot:自定义Jackson ObjectMapper


下一篇:Jackson-databind 反序列化漏洞(CVE-2017-7525)复现