我们在写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