路由元信息

  1. 定义路由的时候可以配置 meta 字段:/foo/bar 这个 URL 将会匹配父路由记录以及子路由记录;
    const router = new VueRouter({
      routes: [
        {
          path: '/foo',
          component: Foo,
          children: [
            {
              path: 'bar',
              component: Bar,
              meta: { requiresAuth: true }
            }
          ]
        }
      ]
    })
    
  2. 访问这个 meta 字段:遍历 $route.matched 来检查路由记录中的 meta 字段;
    // 在全局导航守卫中检查元字段
    router.beforeEach((to, from, next) => {
      if (to.matched.some(record => record.meta.requiresAuth)) {
        if (!auth.loggedIn()) {
          next({
            path: '/login',
            query: { redirect: to.fullPath }
          })
        } else {
          next()
        }
      } else {
        next() // 确保一定要调用 next()
      }
    })
    

重定向

const router = new VueRouter({
  routes: [
    {
      path: '/a',
      //  /a 重定向到 /b
      redirect: '/b'
    },
    {
      path: '/a',
      // 利用命名的路由 /a 重定向到 /b
      redirect: { name: 'foo' }
    },
    {
      path: '/a',
      // 动态返回重定向目标
      redirect: to => {
        // 方法接收 目标路由 作为参数
        // return 重定向的 字符串路径/路径对象
      }
    }
  ]
})

别名

/a 的别名是 /b,意味着,当用户访问 /b 时,URL 会保持为 /b,但是路由匹配则为 /a

const router = new VueRouter({
  routes: [
    {
      path: '/a',
      component: A,
      alias: '/b'
    }
  ]
})

路由组件传参

  1. 存在的问题:组件中使用 $route 会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的 URL 上使用,限制了其灵活性;

  2. 使用 props 解耦:

    export default new Router({
      routes: [
        // 布尔模式:props 被设置为 true,route.params 将会被设置为组件属性
        {
          path: "/user/:id",
          name: "user",
          component: User,
          props: true
        },
        // 对象模式:被按原样设置为组件属性,当 props 是静态的时候有用
        {
          path: "/role",
          name: "role",
          component: Role,
          props: { id: 1 }
        },
        // 函数模式:可以将参数转换成另一种类型,将静态值与基于路由的值结合等等
        {
          path: '/search',
          component: Search,
          props: route => ({ query: route.query.q })
        }
      ]
    });
    
打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

中午好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于前端开发的技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程。

了解更多

目录

  1. 1. 路由元信息
  2. 2. 重定向
  3. 3. 别名
  4. 4. 路由组件传参