定义路由的时候能够配置 meta
字段:数组
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, children: [ { path: 'bar', component: Bar, // a meta field meta: { requiresAuth: true } } ] } ] })
那么如何访问这个 meta
字段呢?ui
首先,咱们称呼 routes
配置中的每一个路由对象为 路由记录。路由记录能够是嵌套的,所以,当一个路由匹配成功后,他可能匹配多个路由记录this
例如,根据上面的路由配置,/foo/bar
这个 URL 将会匹配父路由记录以及子路由记录。spa
一个路由匹配到的全部路由记录会暴露为 $route
对象(还有在导航钩子中的 route 对象)的 $route.matched
数组。所以,咱们须要遍历 $route.matched
来检查路由记录中的 meta
字段。code
下面例子展现在全局导航钩子中检查 meta 字段:component
router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth)) { // this route requires auth, check if logged in // if not, redirect to login page. if (!auth.loggedIn()) { next({ path: '/login', query: { redirect: to.fullPath }//把要跳转的地址做为参数传到下一步 }) } else { next() } } else { next() // 确保必定要调用 next() } })
其实到这和网上大多数的都说的差很少,大多也都只降到这里router
若是你想实现点哪里跳哪里仍是差一步,若是你点user栏目 user栏目是须要登录的 也就是 meta: { requiresAuth: true } 而后跳转登陆 你登录后直接跳user 而不是转跳到首页什么的,你就须要在登录后再执行一个操做对象
$.getJSON( localPath + '/sys/user/info', function (r) { if (r.code == 0) { let redirect = decodeURIComponent(this.$route.query.redirect || '/'); this.$router.push({//你须要接受路由的参数再跳转 path: redirect }); } else { console.error('登陆失败') } } );
顺便的小提示 如何用路由传递参数,必须传递一个对象,不过彷佛只有传递name属性才有效,path是无效的blog
this.$router.push({ name:'order', params:{ orderNum:NO } });
接受上面路由传递的参数路由
let oid =this.$route.params.orderNum;