MJ_*_*les 3 typescript vue.js vue-router
我想知道在将路由传递给 VueRouter 时是否可以定义自定义属性。例如,对于我的应用程序中的大多数路由,我想定义一个如下所示的路由,我可以在其中将组件传递给可选属性“菜单”:
{ path: "/section-stack", component: SectionStack, menu: SectionMenu }
Run Code Online (Sandbox Code Playgroud)
阅读文档指出为此使用元字段,但这并没有达到我想要的效果并导致更详细的路由。查看代码,传递给 VueRouter 的每个路由都是 RouteConfig 类型。是否可以修改我的 VueRouter 以便它可以传递不同类型的路由?即具有附加属性的 RouteConfig 类型。
我认为meta还是要走的路。我曾经用它创建了一个面包屑。我的路线是这样的:
routes: [
{
path: '/',
name: 'home',
component: require('./routes/Home.vue'),
meta: {
history: [],
},
},
{
path: '/projects',
name: 'projects',
component: () => System.import('./routes/Projects.vue'),
meta: {
history: ['home'],
},
},
{
path: '/project/:token',
name: 'project',
component: () => System.import('./routes/project/Overview.vue'),
meta: {
text: (vue) => vue.projects[vue.$route.params.token] || vue.$route.params.token,
to: { name: 'project', params: { token: (vue) => vue.$route.params.token } } ,
history: ['home', 'projects'],
}
]
Run Code Online (Sandbox Code Playgroud)
在我的 vue 组件中,我可以通过观察$route和加载组件来访问元数据,方法是遍历$router对象,如下所示:
export default {
beforeMount() {
this.allRoutes = {};
this.$router.options.routes.forEach(route => {
if (route.name) {
let text = (route.meta && route.meta.text) || route.name;
this.$set(this.allRoutes, route.name, {
text: text,
to: (route.meta && route.meta.to) || { name: route.name }
}
);
}
}
);
},
data() {
return {
allRoutes: {},
currentList: [],
};
},
watch: {
'$route'(to, from) {
this.currentList = ((to.meta && to.meta.history).slice(0) || []);
this.currentList.push(to.name);
}
},
}
Run Code Online (Sandbox Code Playgroud)
特别是forEachinbeforeMount可能是构建菜单的解决方案,fe 基于在元对象中定义的角色。
| 归档时间: |
|
| 查看次数: |
5833 次 |
| 最近记录: |