路由元信息
定义路由的时候可以配置 meta
字段 。
一、通过 meta
定义要验证的路由
const router = new Router({routes: [{path: '/user',component: User,children: [{path: '',name: 'user',component: Profile,meta: { requiresAuth: true }},{path: 'cart',name: 'user-cart',component: Cart,meta: { requiresAuth: true }}]}]
})const isLogin = true;router.beforeEach((to, from, next) => {NProgress.start()if (to.meta.requiresAuth && !isLogin) {next({name: 'login',})} else {next()}})
或者
const router = new Router({routes: [{path: '/user',component: User,meta: { requiresAuth: true }children: [{path: '',name: 'user',component: Profile},{path: 'cart',name: 'user-cart',component: Cart}]}]
})const isLogin = true;router.beforeEach((to, from, next) => {NProgress.start()if (to.matched.some(record => record.meta.requiresAuth) && !isLogin) {next({name: 'login',})} else {next()}})
示例:在全局守卫中,通过路由元信息进行鉴权
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home.vue'
import About from '@/components/About.vue'
import Item from '@/components/Item.vue'
import Login from '@/components/Login.vue'Vue.use(Router)const appRouter = new Router({mode: 'history',routes: [{name: "home",path: '/',component: Home},{name: "about",path: '/about',component: About,// 利用路由元信息进行鉴权meta: {requiresAuth: true}},{// 页面以动态路由形式赋值时:to='{name: "item", params:{id: item.id}}',需要给路由设置name才能赋值name: 'item',// :id配置在route配置时path: '/item/:id',component: Item,// 利用路由元信息进行鉴权meta: {// requiresAuth: true}},{name: "login",path: '/Login',component: Login},]});// 全局守卫(处理如鉴权等需求)
// 当一个导航触发时,全局前置守卫按照创建顺序调用
let user = { id: 1 }
appRouter.beforeEach((to, from, next) => {// 点击About和Item(查看详情)时,需要进行鉴权console.log(to, from);// if (["about", "item"].includes(to.name) || user.id === 0) {// next({ name: 'login' });// }// 利用路由元信息进行鉴权if (to.meta.requiresAuth) {next({ name: 'login' });} else {next();}
})// 在所有组件内守卫和异步路由组件被解析之后被调用
appRouter.beforeResolve((to, from, next) => {next();
})// 导航被确认后调用:因为导航已经被确认,所以没有 next
appRouter.afterEach((to, from) => {})export default appRouter;