1: 全局守卫
使用 router.beforeEach 注册一个全局前置守卫:
const router = new VueRouter({
... })
router.beforeEach((to, from, next) => {
// ...
})
- 回调函数中的参数:
to:进入到哪个路由去 ;
from:从哪个路由离开 ;
next: 决定是否展示你要看到的路由页面 - main.js中设置全局守卫:
*在main.js中,有一个路由实例化对象router。在main.js中设置守卫已是全局守卫。
方案一:
- 在需要触发跳转的路由内设置meta属性,其属性值可设为pathAuth: true
- 判断to. meta. pathAuth 是否存在。
- 存在就判断登录的用户名是否存在? 存在呢就next()直接跳往下一个路由; 如果不存在登录用户名,就next(‘/登录路由名’)
import store from '../store/index.js'
router.beforeEach((to,from,next)=>{
if(to.meta.pathAuth){
//存在
if(store.state.loginName){
next(