1、全局守卫(在所有路由展示前触发)//在main.js中
router.beforeEach((to, from, next) => {
to 即将要进入的到的路由,值为路由
from 离开的路由(从哪个路由离开),值为路由
next 值为函数,这个函数决定你接下来要展示的路由页面
})
router.beforeEach((to, from, next) => {
if(to.path===‘/login‘){
next();
}else{
alert(‘你还没登录,请登录‘);
next(‘/login‘);
}
});
在页面点击时,会先询问,然后跳转。
2、后置钩子(在所有路由展示后触发)//在main.js中
router.afterEach((to,from)=>{
to 即将要进入的到的路由,值为路由
from 离开的路由(从哪个路由离开),值为路由
});
router.afterEach((to, from) => {
alert(‘我是后置钩子‘)
})
3、路由独享的守卫(在当前路由展示前触发)//在router.js
beforeEnter(to, from, next){ //在路由内部使用
to 即将要进入的到的路由,值为路由
from 离开的路由(从哪个路由离开),值为路由
next 值为函数,这个函数决定你接下来要展示的路由页面
};
beforeEnter(to,from,next){
alert(‘非登录状态下无法管理,请登录‘);
next(‘/login‘);
}
4、组件内的守卫
beforeRouteEnter(to, from, next){ //在路由组件内使用
//在当前路由被展示前调用
};
beforeRouteUpdate(to, from, next){ //在路由组件内使用
//在当前路改变时调用
};
beforeRouteLeave(to, from, next){ //在路由组件内使用
//在离开当前路时调用
};
beforeRouteEnter(to, from, next){ //在路由组件内使用
//在当前路由被展示前调用
//alert(‘你好!‘);
//alert(this.name); //报错,beforeRouteEnter不能够访问到this对象,因为守卫触发时组件还没有被创建
next(vm=>{
alert(vm.name);
});
},
离开页面时调用
beforeRouteLeave (to, from, next) {
// 在离开当前路由时调用
const answer=confirm(‘你确定要离开么?‘)
if(answer){
next();
}else{
next(false);
}
}
原文:https://www.cnblogs.com/colorful-paopao1/p/11423655.html