Vue项目中Router路由中meta字段的妙用-案例

用Vue做网站登录验证时常用到Vue-Router官方路由器管理,这时候会调用beforeEach函数

// 登录验证
beforeEach((to,from,next) =>{
      if(to.path === '/music'){    //页面path为 '/music',就让它跳转到 '/login'登录页面
          next({/login})
      }else{
          next()
      }
})

上述功能单一,且不便于扩展

根目录是/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((item)=>{
            return item.meta.requiresAuth    //如果是item 下面 meta 带有requiresAuth字段的组件都能跳转到 '/login'目录下
      })){
            next("/login")
      }else{
        next()
      }
})

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JackieDYH

谢谢您嘞!我会继续加油地

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值