Vue Router的使用(二)

129 阅读2分钟

「这是我参与2022首次更文挑战的第14天,活动详情查看:2022首次更文挑战」。

在上一篇文章Vue Router的使用(https://juejin.cn/post/7062606632642936846)中介绍了vue-router的一些基本用法,比如,动态路由,路由跳转,路由替换,历史路由跳转等,这篇文章中我们继续看一下更深的用法吧~

命名路由

可以给路由提供 name,这样就是有名字的路由啦。

  • params 的自动编码/解码。
  • 防止你在 url 中出现打字错误。
  • 绕过路径排序(如显示一个)
const routes = [
  {
    path: '/student/:studentname',
    name: 'student',
    component: Student
  }
]

跳转到一个命名的路由的时候

  • 通过 router-link 组件的 to 属性传递一个对象
<router-link :to="{ name: 'student', params: { studentname: 'lmw' }}">
  Student
</router-link>
  • 代码调用 router.push() 
router.push({ name: 'student', params: { studentname: 'lmw' } })

这两种方式都可以实现路由导航到路径 /student/lmw

命名视图

当需要同时展示多个视图,而不是嵌套展示的时候,比如,有 sidebar (左侧菜单) 和 main (主内容) 两个视图,这时就可以用命名视图。可以在界面中拥有多个单独命名的视图,而不是只有一个单独的出口。如果 router-view 没有设置名字,默认为 default

<router-view class="view left-sidebar" name="LeftSidebar"></router-view>
<router-view class="view main-content"></router-view>
<router-view class="view right-sidebar" name="RightSidebar"></router-view>

一个视图用一个组件渲染,对于同一个路由,多个视图就需要多个组件。确保正确使用 components 配置

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      components: {
        default: Home,
        LeftSidebar,
        RightSidebar,
      },
    },
  ],
})

重定向和别名

重定向也是通过 routes 配置来完成

const routes = [{ path: '/home', redirect: '/' }]

重定向的目标也可以是一个命名的路由

const routes = [{ path: '/home', redirect: { name: 'homepage' } }]

或者是一个方法,动态返回重定向目标

const routes = [
  {
    path: '/search/:searchText',
    redirect: to => {
      // 方法接收目标路由作为参数
      // return 重定向的字符串路径/路径对象
      return { path: '/search', query: { q: to.params.searchText } }
    },
  },
  {
    path: '/search',
  },
]

将 props 传递给路由组件

在你的组件中使用 $route 会与路由紧密耦合,这限制了组件的灵活性,因为它只能用于特定的 URL。我们可以通过 props 配置来解除这种行为:

const Student = {
  template: '<div>Student {{ $route.params.id }}</div>'
}
const routes = [{ path: '/student/:id', component: Student }]

替换成

const Student = {
  props: ['id'],
  template: '<div>Student {{ id }}</div>'
}
const routes = [{ path: '/student/:id', component: Student, props: true }]

以上就是vue-router的一些基本配置了,记录一下,温故而知新。