全局前置守卫
pageA -----守卫----> pageB
路由跳转之前, 会触发一个函数
语法:router.beforeEach((to, from, next) => {})
案例:
在跳转路由前, 判断用户登陆了才能去<我的音乐>页面, 未登录弹窗提示回到发现音乐页面
实现:
● 在router/index.js 路由对象上使用固定方法beforeEach
// 路由守卫
// 每次页面跳转,都会执行这个回调
router.beforeEach((to, from, next) => {
console.log(to, from)
// to代表要跳转到哪个路径去, to的值是个对象可以打印看到
// from代表从哪个路径跳过去
// next是一个函数。
// next() 放行;
// next('路由地址') 跳到指定的位置
// 判断,是否有权限去访问页面,如果没有权限,跳转到登录页
const token = localStorage.getItem('token') // 假设token
// 访问login不要token,其他都要
if(to.path === '/login'){
next()//此处不能写 next('/login')会死循环报错
} else {
// 不去login,就要检查一下证件
if(token){
next() // 有token就正常访问
} else {
next('/login')
}
}
})
补充/login对应的页面
<template>
<div>
<h2>登录</h2>
<button @click="login">芝麻开门</button>
</div>
</template>
<script>
export default {
methods: {
login(){
// 1. 设置token
localStorage.setItem('token', '123')
// 2. 页面跳转
this.$router.push('/find/list')
}
}
}
</script>
死循环报错:
全局后置守卫
路由跳转后, 触发的函数
语法:router.afterEach((to, from) => {})
使用:
router/index.js - 添加
router.afterEach((to, form) => {
console.log(to);
console.log(form);
console.log("路由发生了跳转");
})