在router下面的index.js中添加
meta: {
requireauth: true, // 判断是否需要登录
},
用来判断需要是否登录, 在login也就不用添加了
import Vue from "vue";
import VueRouter from "vue-router";
import Router from "vue-router";
const routes = [
{
path: "/about",
name: "About",
component: () =>
import(/* webpackChunkName: "about" */ "../views/About.vue"),
children: [
{
path: "/home",
name: "home",
meta: {
requireauth: true, // 判断是否需要登录
},
component: () =>
import(/* webpackChunkName: "home" */ "../views/home/Home.vue"),
},
}
]
在main.js中:
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requireauth)) {
// 判断该路由是否需要登录权限
// console.log("需要登录");
if (document.cookie.split("token=")[1]) {
// 判断当前的token是否存在 ; 登录存入的token
next();
} else {
next({
path: "/",
query: { redirect: to.fullpath }, // 将跳转的路由path作为参数,登录成功后跳转到该路由
});
}
} else {
next();
}
});
我这里是用token 判断cookie中token是否存在, 不存在的话就跳转到登录页