$route.matched

    <router-link
     class="icon-go"
     :to="{ name: '首页'}"
     v-if="$route.matched[0].path=='/category'">
    </router-link>
    <span class="icon-go" @click="$router.go(-1)" v-else></span>
    <slot name="title"></slot>   </header> </template> ```

$route.path
类型: string
字符串,对应当前路由的路径,总是解析为绝对路径,如 /foo/bar。

$route.params
类型: Object
一个 key/value 对象,包含了动态片段和全匹配片段,如果没有路由参数,就是一个空对象。

$route.query
类型: Object
一个key/value 对象,表示 URL 查询参数。例如,对于路径/foo?user=1,则有 $route.query.user == 1,如果没有查询参数,则是个空对象。

$route.matched
类型:Array
一个数组,包含当前路由的所有嵌套路径片段的路由记录 。路由记录就是 routes 配置数组中的对象副本 (还有在 children 数组)。

const router = new VueRouter({
  routes: [
    // 下面的对象就是路由记录
    { path: '/foo', component: Foo,
      children: [
        // 这也是个路由记录
        { path: 'bar', component: Bar }
      ]
    }
  ]
})

当 URL 为 /foo/bar,$route.matched 将会是一个包含从上到下的所有对象 (副本)。

$route.fullPath
路由是:/path/:type真正路径是:/path/list
path匹配路径: /path/list
fullPath匹配路由: /path/:type

路由元信息 .meta

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          // a meta field
          meta: { requiresAuth: true ,keepAlive:true}//1.权限 2.内存缓存,单页面切换
        }
      ]
    }
  ]
})

先理解什么是路由记录 : 路由记录就是 routes 配置数组中的对象副本 (还有在 children 数组)。

上方代码中的路由记录见下方:

    //一级路由 
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          // a meta field
          meta: { requiresAuth: true ,keepAlive:true}//1.权限 2.内存缓存,单页面切换
        }
      ]
    }
 
 
//一级路由的子路由
 
    { path: 'bar',component: Bar,meta: { requiresAuth: true ,keepAlive:true } }
 
 
//两者都是    路由记录

定义路由的时候可以配置 meta 字段
根据上面的路由配置,/foo/bar 这个 URL 将会匹配父路由记录以及子路由记录
一个路由匹配到的所有路由记录会暴露为 $route 对象 (还有在导航守卫中的路由对象) 的 $route.matched 数组。
检查路由记录中的 meta 字段 ,我们需要遍历 $route.matched

$route.matched
一个数组,包含当前路由的所有嵌套路径片段的路由记录
一个路由匹配到的所有路由记录会暴露为 $route 对象 (还有在导航守卫中的路由对象) 的 $route.matched 数组

路由元信息 .meta $route.matched 搭配路由守卫 进行验证

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()
  }
})

借鉴 添加链接描述

发布了56 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44317018/article/details/105626280