vue导航守卫

1、更具项目要求写导航守卫文件 permission.js

import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import { bindWeChat } from "@/api/userCenter/personalCenter";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = [
  "/screen",
  "/login",
  "/register",
  "/forget",
  "/invite",
  "/addTeam",
  "/updatePassword",
  "/bindAccount"
]; // 白名单
/**
 * 路由拦截
 * 权限验证
 */
let hasRoles = false;
router.beforeEach(async (to, from, next) => {
  if (
    window.location.href.indexOf("code") >= 0 &&
    to.path === "/login" &&
    from.path === "/login"
  ) {
    let code = window.location.href.split("?")[1].split("&")[0];
    code = code.substring(5);
    store.state.wxCode = code;
    store
      .dispatch("user/login", {
        account: code,
        type: 3,
        platform: 1
      })
      .then(() => {
        router.push({ path: "/" });
      });
  }

  // start progress bar
  NProgress.start();
  // set page title
  document.title = await getPageTitle(to.meta.title);
  // determine whether the user has logged in
  const hasToken = getToken();
  if (to.path === "/invite") {
    next({ query: to.query });
  }
  if (hasToken) {
    if (to.path === "/login") {
      // if is logged in, redirect to the home page
      next({ path: "/" });
      NProgress.done();
    }
    if (to.path === "/updatePassword") {
      next();
    } else {
      if (hasRoles) {
        // 去往详情页的时候需要缓存组件,其他情况下不需要缓存 --->(需要提前加入缓存,因为第一次加入的数据是之前的)
        // console.log('是否需要缓存:' + to.meta.keepAlive, to, to.meta.title)
        if (to.meta.keepAlive) {
          store.dispatch("permission/changeComponents", [
            to.meta.keepAliveName
          ]);
        } else if (!to.meta.keepAlive) {
          store.dispatch("permission/changeComponents", []);
        }
        // console.log('加入的数组', store.state.permission.catchComponents)
        next();
      } else {
        try {
          if (from.path !== "/login" || to.path !== "/login") {
            await store.dispatch("user/getInfo");
            await store.dispatch("user/getConfig");
          }
          // get user info
          //     await store.dispatch("user/getInfo");
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const userMenu = await store.dispatch("user/menuLoad");
          // console.log('userMenu',userMenu)
          // generate accessible routes map based on roles
          // const userRoutes = await store.dispatch('permission/generateRoutes', JSON.parse(menu))
          // dynamically add accessible routes
          const errorPage = { path: "*", redirect: "/404", hidden: true };
          router.options.routes.push(...userMenu, errorPage);
          // router.options.routes.push()
          router.addRoutes([...userMenu, errorPage]);
          // eslint-disable-next-line
          hasRoles = true;
          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next(to.path, true);
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch("user/resetToken");
          Message.error(error || "Has Error");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});

2、在mian.js文件中引入

import '@/permission'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值