Vue router 全局路由守卫

  1. 记录一下全局路由守卫的使用:
    节选: 定义一个数组用于检测与管理需要登录的页面,全局路由守卫配合本地存储判断是否跳转
    在这里插入图片描述
    2、用例
import Vue from 'vue'
import Router from 'vue-router'
import store from './../store'

import Home from 'components/home/home' // 主页组件

// 其它组件...

import Cart from 'components/cart/cart' // 购物车组件
import User from 'components/user/user' // 用户中心组件

// 其他组件...

import GoodsDetail from 'components/goods-detail/goods-detail' // 商品详情组件

import { localTake } from 'common/js/localStore' // 本地存储方法封装

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/', // 默认地址
      redirect: '/home'
    },
    {
      path: '/home',
      component: Home,
      name: 'Home',
      meta: {
        title: '主页',
        keepAlive: true // 需要被缓存
      }
    },
    {
      path: '/cart',
      component: Cart,
      name: 'Cart',
      meta: {
        title: '购物车',
        keepAlive: true // 需要被缓存
      }
    },
    {
      path: '/user',
      component: User,
      name: 'User',
      meta: {
        title: '我的',
        keepAlive: true // 需要被缓存
      }
    },
    {
      path: '/user-login',
      component: UserLogIn,
      name: 'UserLogIn',
      meta: {
        title: '登录',
        keepAlive: false // 不需要被缓存
      }
    },
    {
      path: '/goods-detail',
      component: GoodsDetail,
      name: 'GoodsDetail',
      meta: {
        title: '商品详情',
        keepAlive: true // 需要被缓存
      }
    }
  ],
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return {x: 0, y: 0}
    }
  }
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const nextRoute = ['User', 'Cart', 'GoodsDetail'] // 需要登录的页面
  let isLogin = localTake('userMsg')  // 判断是否登录,本地存储有用户数据则视为已经登录
  // 未登录状态;当路由到 nextRoute 指定页时,跳转至 UserLogIn
  if (nextRoute.indexOf(to.name) >= 0) { // 检测是否登录的页面
    if (!isLogin) { // 如果未登录(本地存储无用户数据),并且要跳到登录页面
      if (from.name === 'UserLogIn') {
        next('/')
        return
      }
    // 登录后,跳到到当前页面
      router.push({
        name: 'UserLogIn',
        params: {redirect: to.fullPath}  
      })
    }
  }
  // 已登录状态;当路由到 UserLogIn 时,跳转至 Home
  if (to.name === 'UserLogIn') {
    if (isLogin) {
      next('/')
      return
    }
  }
  next() // 必须使用 next ,执行效果依赖 next 方法的调用参数
})

export default router

3、实际使用

router.beforeEach((to, from, next) => {
  // to and from are both route objects. must call `next`.
  if (to.path != "/") {
    // 校验用户是否登录
   if (helper.getTypes(store.getters.getLoginUser) === "object") {
   //getTypes为导入的方法
   //import  helper from '../src/helper';  在helper.js定义了方法
          next();
   } else {
     next("/");

   } else {
     
     next();
   }
  }
});
发布了75 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_45416217/article/details/102949660