yb课堂 实战之路由拦截和订单模块 《四十二》
前置守护 路由拦截功能开发
文档:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
router里面配置需要登陆的路由
meta: { requiresAuth:true }
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home/Home.vue' import CourseDetail from '../views/CourseDetail/CourseDetail.vue' import Login from '../views/Login/Login.vue' import Order from '../views/Order/Order.vue' import Pay from '../views/Pay/Pay.vue' import Personal from '../views/Personal/Personal.vue' import Register from '../views/Register/Register.vue' Vue.use(VueRouter) const routes = [ { path: "/", name: "Home", component: Home }, { path: "/coursedetail", name: "CourseDetail", //按需加载 component: ()=>import("../views/CourseDetail/CourseDetail") //component: CourseDetail }, { path: "/login", name: "Login", component: Login }, { path: "/order", name: "Order", component: Order, meta: { requiresAuth:true } }, { path: "/pay", name: "Pay", component: Pay, meta: { requiresAuth:true } }, { path: "/personal", name: "Personal", component: Personal, meta: { requiresAuth:true } }, { path: "/register", name: "Register", component: Register } ] const router = new VueRouter({ routes }) export default router
main.js里面配置路由拦截
//拦截拦截,拦截全部路由,每次操作路由都是被拦截进行判断 router.beforeEach((to, from, next) => { const token = localStorage.getItem('token'); //筛选需要传token的路由,匹配route里面需要登陆的路由,如果匹配到就是true if (to.matched.some(record => record.meta.requiresAuth)) { //根据token是否有,帕努单是否需要调到登陆页面 if (token) { next(); } else { next({ path: '/login' }) } }else { next(); } })