全局路由守卫:
router.beforeEach((to,from,next) => {
// to: 即将要进入的路由对象
// from: 即将要离开的路由对象
// next():是一个函数,在路由拦截中一定要注意调用next()进入下一个步骤,要确保进入next
// next()- 进入下一个钩子函数,next(false) - 中断当前路由导航,
next({path: '/luyou',replace: true})||next({path: '/luyou'}) - 中断当前导航,跳转至下一个路由地址
})
import Vue from 'vue';
import Router from 'vue-router';
const router = new Router ({
routes: [
{
path: '/foo',
component: Foo,
children: [
{
path: 'bar',
component: Bar,
meta: { requiresAuth: true , title: '导航页面1'} // 需要登录
},
{
path: 'bar1',
component: Bar1,
meta: { requiresAuth: false , title: '导航页面2'} // 无需登录
},
]
}
]
})
router.beforeEach((to, from, next) => {
to里有你想要东西,打印出来可以看到。需要判断可以自行处理
// 通过requiresAuth判断当前路由导航是否需要登录
以下代码可以根据自己需求进行判断,但整体思路是可以参考的
if (to.matched.some(record => record.meta.requiresAuth)) {
// 若需要登录访问,检查是否为登录状态
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // 确保一定要调用 next()
}
})
export default router;
路由独享的守卫
对单个路由进行控制判断
import Vue from 'vue';
import Router from 'vue-router';
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
书写业务逻辑代码
// ...
}
}
]
})
组件内的守卫
代码放到当前组件内自动运行
有三种情况:
1.进入组件之前:
beforeRouteEnter
export default {
data(){
return{
infor:'你好'
}
},
beforeRouteEnter:(to,from,next)=>{
// 在渲染该组件的对应路由被 confirm 前调用
// 不能获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
//此时该组件还没被实例化
alert(this.infor); //弹出消息框信息为 undefined
next(vm =>{
//此时该组件被实例化了
alert(vm.infor); //弹出消息框信息
})
}
}
2.组件被复用时调用
beforeRouteUpdate
beforeRouteUpdate (to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
},
3.离开组件之后
beforeRouteLeave
export default {
beforeRouteLeave(to,from,next){
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
if(confirm("确定离开吗?") == true){
next(
item=>{ 可以编辑业务代码 }
) //跳转到另一个路由
}else{
next(false);//不跳转
}
}
}