我们在用Vue做网站登录验证时常用到Vue-Router官方路由器管理,这时候会调用beforeEach函数
beforeEach((to,from,next) =>{
if(to.path === '/music'){ //页面path为 '/music',就让它跳转到 '/login'登录页面
next({/login})
}else{
next()
}
})
上面的代码只在需要登录验证的网页只有/goodsList一个网页时天衣无缝,但是像这种需要登录验证的网页很多怎么办?比如说有一个平台,有多种功能,有的功能用户登陆后才能体验,有的不需要登录,如下载音乐、分享音乐、购买音乐时需要跳转到登录页面,听音乐,搜索音乐时不需要登录时,这种 if ...else方法显然不适合,原因有两个:
1.像我在上面举例的需要登录验证的网页很多的话那么在if条件里得写下所有的路由地址,将会是非常麻烦的一件事情
- 因为路径是嵌套的,根目录下有二级目录,三级目录……,比如 '/music/download' , '/music/buy' , '/music/share'情况下,像上面的代码一样只是在 path :'/music' 情况下就非常简单,构成不了限制条件,不会受到验证就已经登上去了,
所以我的想法就是根目录是/music的所有路径都会受到限制,这就是vue router中meta 字段(路由元信息)存在的意义
在 beforeEach(to,from,next){}钩子函数中
-
to 和 from 都是路由对象,路由对象有以下对象属性:
-
$route.path
类型: string
字符串,对应当前路由的路径,总是解析为绝对路径,如 "/foo/bar"。 -
$route.params
类型: Object
一个 key/value 对象,包含了动态片段和全匹配片段,如果没有路由参数,就是一个空对象。 -
route.query.user == 1,如果没有查询参数,则是个空对象。
-
$route.hash
类型: string
当前路由的 hash 值 (带 #) ,如果没有 hash 值,则为空字符串。 -
$route.fullPath
类型: string
完成解析后的 URL,包含查询参数和 hash 的完整路径。 -
$route.matched
类型: Array<RouteRecord>
我们用这些路由对象属性就能够限制根目录为 /music的所有页面了
import Vue from 'vue'
import Router from 'vue-router '
Vue.user(Router)
const router = new Router({
routes:[
{
path:'/login',
component:()=>import(@/pages/Login/template.vue)
},
{
path:'/music',
component:() => import(@/pages/Music/template.vue) ,
meta: { requiresAuth: true }
},
Children:[
{
{
path:'/download',
component:() => import(@/pages/Download/template.vue) ,
meta: { requiresAuth: true }
},
{
path:'/share',
component:() => import(@/pages/Share/template.vue) ,
meta: { requiresAuth: true }
},
{
path:'/buy',
component:() => import(@/pages/Buy/template.vue) ,
meta: { requiresAuth: true }
},
},
{
path:'/listen',
component:() => import(@/pages/Listen/template.vue)
},
{
path:'/index',
component:() => import(@/pages/Index/template.vue)
},
{
path:'/detail',
component:() => import(@/pages/Detail/template.vue)
},
]
})
router.beforeEach((to,from,next) => {
if(to.matched.some(function(item){
return item.meta.requiresAuth //如果是item 下面 meta 带有requiresAuth字段的组件都能跳转到 '/login'目录下
})){
next(/login)
}else{
next() //这一行next必须写
}
})
网友评论