joken-前端工程师

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::
  404 随笔 :: 39 文章 :: 8 评论 :: 20万 阅读
  • autoNamePlugin.js
export default {
    install: (app) => {
        const router = app.config.globalProperties.$router;

        if (router) {
            router.beforeEach(async (to, from, next) => {
                try {
                    // 获取匹配到的路由组件
                    const matchedComponents = to.matched;

                    for (const record of matchedComponents) {
                        if (record.components?.default) {
                            // 如果是异步组件,需要等待它加载完成
                            if (typeof record.components.default === 'function') {
                                const Component = await record.components.default();
                                // 为实际的组件设置名称
                                if (Component?.default) {
                                    Component.default.name = record.name;
                                }
                            } else {
                                // 同步组件直接设置
                                record.components.default.name = record.name;
                            }
                        }
                    }
                    next();
                } catch (error) {
                    console.error('Error in autoNamePlugin:', error);
                    next();
                }
            });
        }
    }
};

  • main.js
import autoNamePlugin from './plugins/autoNamePlugin';

...
app.use(autoNamePlugin);
...

目的是为了路由表的name自动给引入的页面组件同步命名同样的命名。

posted on   joken1310  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示