vue路由动画切换页面无法读取meta值的bug
在vue项目的二级路由中,想要通过设置路由表中的meta值,来判断页面的slide-left 和slide-right的方向。
对于从左到右的排列,给routes依次设为1,2,3,4…的值,使其可以通过大小来判断from和to,并显示出不同的划入 / 划出效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | { path: 'aaa' , name: 'aaa' , component: aaa, meta:1 }, { path: 'bbb' , name: 'bbb' , component: bbb, redirect: 'bbb/baba' , meta:2, children: [ { path: 'baba' , name: 'baba' , component: baba }, { path: 'ccc' , name: 'ccc' , component: ccc }, { path: 'ddd' , name: 'ddd' , component: ddd }, { path: 'eee' , name: 'eee' , component: eee }, { path: 'fff' , name: 'fff' , component: fff }], }, { path: 'ggg' , name: 'ggg' , meta:4, component: ggg }, { path: 'hhh' , name: 'hhh' , meta:3, component: hhh }, |
然鹅,
在设置的过程中,其中一个路由始终无法读到all这个路由中的meta:2
导致切换路由的动画效果出了问题
问题原因
读不到的meta的是因为设置了子路由以及重定向。
解决方法
把meta值加在它的子路由上,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | { path: 'bbb' , name: 'bbb' , component: bbb, redirect: 'bbb/baba' , //meta:2, children: [ { path: 'baba' , name: 'baba' , component: baba, meta:2 }, { path: 'ccc' , name: 'ccc' , component: ccc }, { path: 'ddd' , name: 'ddd' , component: ddd }, { path: 'eee' , name: 'eee' , component: eee }, { path: 'fff' , name: 'fff' , component: fff }], }, |
vue路由元信息meta
路由元信息
定义路由的时候可以配置meta字段。
那么我们可以利用meta字段来做什么呢?
设置title
1 2 3 4 5 | name: 'category' , component: () => import ( './view/creatBrainStorm/creat/category' ), meta: { title: '卓脑' } |
我们可以在钩子函数router.beforeEach中获取meta中的title数据,并设置为页面标题。
1 2 3 4 5 6 | router.beforeEach((to, from, next) => { const title = to.meta && to.meta.title if (title) { document.title = title } } |
权限校验(例:登录校验)
1 2 3 4 5 6 7 8 | { name: 'cart' , component: () => import ( './view/cart' ), meta: { title: '购物车' , requireAuth: true // 当有这个字段的时候,我们就认为这个路由页面是要有登录权限的 } } |
检查meta中元字段:
1 2 3 4 5 6 7 8 9 10 11 12 13 | if (to.meta.requireAuth) { // 不直接通过本地缓存进行判断,而是通过Vuex的属性状态进行判断 if (store.state.user.token) { next() } else { next({ path: '/login' , query: { redirect: to.fullPath } }) } } else { next() } |
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。