全局路由守卫根据token判断登录状态进行拦截(简易版)

我们在写vue项目的时候,很多页面需要根据判断你是否登录,然后再进行添加购物车啊,收藏啊一系列的操作。。。这个时候使用路由守卫去判断是否有token值进行拦截就显得至关重要。。今天说的这个比较易理解,好使用。。
router文件中index.js 中模板模拟:

import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/main/Home.vue";

Vue.use(VueRouter);

const routes = [{
    path: "/",
    redirect: "/home"
  },
  {
    path: "/home",
    name: "Home",
    component: Home,
    meta: {
      isShow: true
    }
  },
 
  //课程页面
  {
    path: "/about",
    name: "About",
    component: () =>
      import("../views/main/About.vue"),
    meta: {
      isShow: true
    }

  },
  {
    path: "/third",
    name: "Third",
    component: () =>
      import("../views/main/Third.vue"),
    meta: {
      isShow: true
    }
  },
  // 练习页面
  {
    path: "/practice",
    name: "Practice",
    component: () =>
      import("../views/main/priactice_detail/Practice.vue"),
    meta: {
      isShow: true
    }
  },
  {
    path: "/mine",
    name: "Mine",
    component: () =>
      import("../views/main/mine_page/Mine.vue"),
    meta: {
      isShow: true
    },

  },
  // 进入登录页面
  {
    path: "/login",
    name: "Login",
    component: () =>
      import("../views/main/login_page/Login.vue"),
    meta: {
      isShow: false
    }
  },
 
];

const router = new VueRouter({
  mode: "hash",
  base: process.env.BASE_URL,
  routes
});


router.beforeEach(function (to, from, next) {
  //判断是否存在token值,不存在就去登录页面去登录
  if (!localStorage.getItem("token2")) {
    if (to.path !== "/login") {
      return next("/login")
    }
  }
  //如果存在就执行下一步
  next()
})
export default router;

其实重要代码就这些:

router.beforeEach(function(to, from, next) {
    if (!localStorage.getItem("loginName")) {
        if (to.path !== '/login') {
            return next('/login')
        }
    }
    next()
})

有关vue路由 导航守卫的一些具体的详细解释:
可以参考这个网址:
https://www.jianshu.com/p/691379025334

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值