vue路由导航守卫
一.设置全局前置路由守卫
在index.js中配置
import { Toast } from "vant";
Vue.use(Toast);
//全局前置守卫
router.beforeEach((to, from, next) => {
let token = localStorage.getItem("token"); //验证登录状态
if (token) {
//判断是否登录
next();
} else {
if (to.path !== "/login" && to.path !== "/register") {
Toast("请先登录");
next({ path: "/login" });
} else {
next();
}
}
});
二.路由独享的守卫
实现先实名认证在进入身份页面
{
path: "/physical",
name: "physical",
component: physical,
meta: {
showFooter: true,
},
beforeEnter: (to, from, next) => {
let IdCard = localStorage.getItem("IdCard");
if (IdCard) {
next();
} else {
if (to.path !== "/autonym") {
Toast("请先实名认证");
next({ path: "/autonym" });
} else {
next();
}
}
},
},
三.组件内的守卫
vue.js传送门:https://router.vuejs.org/zh/guide/advanced/navigation