vue的路由动画切换页面无法读取meta值的bug记录(vue动态路由跳转报错)这样也行?

随心笔谈11个月前发布 admin
95 0



目录vue路由动画切换页面无法读取meta值的bug问题原因解决方法vue路由元信息meta路由元信息设置title权限校验(例:登录校验)总结

在vue项目的二级路由中,想要通过设置路由表中的meta值,来判断页面的slide-left 和slide-right的方向。

对于从左到右的排列,给routes依次设为1,2,3,4…的值,使其可以通过大小来判断from和to,并显示出不同的划入 / 划出效果

{
?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值加在它的子路由上,

{
?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
?}],
},

定义路由的时候可以配置meta字段。

那么我们可以利用meta字段来做什么呢?

? ? name: ‘category’,
? ? component: ()=> import(‘https://www.jb51.net/javascript/view/creatBrainStorm/creat/category’),
? ? meta: {
? ? ? title: ‘卓脑’
? ? }

我们可以在钩子函数router.beforeEach中获取meta中的title数据,并设置为页面标题。

router.beforeEach((to, from, next)=> {
? const title=to.meta && to.meta.title
? if (title) {
? ? document.title=title
? }
}
{
? ? name: ‘cart’,
? ? component: ()=> import(‘https://www.jb51.net/javascript/view/cart’),
? ? meta: {
? ? ? title: ‘购物车’,
? ? ? requireAuth: true // 当有这个字段的时候,我们就认为这个路由页面是要有登录权限的
? ? }
? }

检查meta中元字段:

if (to.meta.requireAuth) {
? ? // 不直接通过本地缓存进行判断,而是通过Vuex的属性状态进行判断
? ? if (store.state.user.token) {
? ? ? next()
? ? } else {
? ? ? next({
? ? ? ? path: ‘/login’,
? ? ? ? query: { redirect: to.fullPath }
? ? ? })
? ? }
? } else {
? ? next()
? }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:vue2.0路由切换后页面滚动位置不变BUG的解决方法解决vue-router在同一个路由下切换,取不到变化的路由参数问题Vue 路由切换时页面内容没有重新加载的解决方法

© 版权声明

相关文章