Using meta
is still my preferred approach. I once utilized it to create a breadcrumb navigation. My routing structure looked like this:
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'],
}
]
Within my Vue component, I was able to access the meta data by monitoring the $route
and navigating through the $router
object while the component was loading, like so:
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);
}
},
}
The forEach
loop in the beforeMount
section could be particularly useful for constructing a menu based on roles defined in the meta object.