0
点赞
收藏
分享

微信扫一扫

全局后置__路由守卫

简介:

在初始化后被调用,跳转路由之后被调用

实现效果:

跳转到哪个路由哪个路由页的tilte改变文本

全局后置__路由守卫_初始化

 

 实例:

import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";
import aboutone from './views/Aboutone';
import abouttow from './views/Abouttow';
import aboutoneson from './views/Aboutoneson';

Vue.use(Router);

const router =new Router({
routes: [{
// 页面开始就显示的路由
path: "/",
name: "home",
component: Home,
meta:{isAuth:false,title:'主页'},
},
{
path: "/about",
name: "about",
component: () =>
import("./views/About.vue"),
meta:{isAuth:false,title:'关于'},
children: [{
name:'xiaoxi',
path: 'aboutone',
component: aboutone,
// 需要校验就写
meta:{isAuth:true,title:'列表一'},
children:[
{
path: 'aboutoneson',
component: aboutoneson,
meta:{isAuth:true,title:'详情'},
}
]
},
{
name:'abtow',
path: 'abouttow',
component: abouttow,
meta:{isAuth:true,title:'列表二'},
},
]
}
]
});
// 前置路由守卫
router.beforeEach((to,from,next)=>{
console.log('前置',to,from);
//判断如果在路由上meta.isAuth为true'为true就开始校验,
if (to.meta.isAuth){
document.title = to.meta.title || '路由练习'
// 如果本地存储的Nuber值为yang就跳转,反之弹出权限不够
if (localStorage.getItem('Nuber') === 'ycng') { //故意改的值
next()
} else{
alert('权限不够')
}
} else{
document.title = to.meta.title || '路由练习'
next()
}
})
// 后置路由守卫 初始化后被调用,跳转路由后被调用
// 后置守卫没有next参数
router.afterEach((to,from)=>{
console.log('后置',to,from);

})
export default router

 这时出现了一个bug当点击权限不够后tilte还是改变了路由没有跳转

全局后置__路由守卫_初始化_02

 

 

解决:

 只需要把前置那里的 document.title = to.meta.title || '路由练习' 添加到后置路由守卫就解决了

// 前置路由守卫
router.beforeEach((to,from,next)=>{
console.log('前置',to,from);
//判断如果在路由上meta.isAuth为true'为true就开始校验,
if (to.meta.isAuth){
// 如果本地存储的Nuber值为yang就跳转,反之弹出权限不够
if (localStorage.getItem('Nuber') === 'yng') {
next()
} else{
alert('权限不够')
}
} else{
next()
}
})
// 后置路由守卫 初始化后被调用,跳转路由后被调用
// 后置守卫没有next参数
router.afterEach((to,from)=>{
console.log('后置',to,from);
document.title = to.meta.title || '路由练习'

})
export default router

全局后置__路由守卫_Vue_03

 



举报

相关推荐

0 条评论