Vue-router笔记

  • 动态路径参数(dynamic segment) 以冒号开头
    例如:

    1
    2
    3
    4
    // id 为动态
    routes: [
    { path: '/user/:id', component: User }
    ]
  • 路由中设置的多段“路径参数”,对应的值都会设置到this.$route.params里。

  • 当使用一个通配符时,$route.params 内会自动添加一个名为 pathMatch 参数。它包含了 URL 通过通配符被匹配的部分.
    例如:

    1
    2
    3
    4
    5
    6
    // 给出一个路由 { path: '/user-*' }
    this.$router.push('/user-admin')
    this.$route.params.pathMatch // 'admin'
    // 给出一个路由 { path: '*' }
    this.$router.push('/non-existing')
    this.$route.params.pathMatch // '/non-existing'
  • 如果有子路由 children, 则要嵌套<router-view></router-view>标签

  • router.push() 需要注意的地方

    • 如果提供了 pathparams会被忽略,pathparams不能同时使用.
      1
      2
      // 这里的 params 不生效
      router.push({ path: '/user', params: { userId }}) // -> /user
    1
    2
    3
    const userId = '123'
    router.push({ name: 'user', params: { userId }}) // -> /user/123
    router.push({ path: `/user/${userId}` }) // -> /user/123
    1
    2
    // 带查询参数,变成 /register?plan=private
    router.push({ path: 'register', query: { plan: 'private' }})
  • 命名视图:一个视图使用一个组件渲染,因此对于同个路由,多个视图就需要多个组件。确保正确使用 components 配置 (带上 s):

例如:

1
2
3
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>

1
2
3
4
5
6
7
8
9
10
11
12
const router = new VueRouter({
routes: [
{
path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
}
]
})
  • 重定向有三种表达

    • 1
      2
      3
      4
      5
      const router = new VueRouter({
      routes: [
      { path: '/a', redirect: '/b' }
      ]
      })
    • 1
      2
      3
      4
      5
      const router = new VueRouter({
      routes: [
      { path: '/a', redirect: { name: 'foo' }}
      ]
      })
    • 1
      2
      3
      4
      5
      6
      7
      8
      const router = new VueRouter({
      routes: [
      { path: '/a', redirect: to => {
      // 方法接收 目标路由 作为参数
      // return 重定向的 字符串路径/路径对象
      }}
      ]
      })
    • 注意导航守卫并没有应用在跳转路由上,而仅仅应用在其目标上。

    • 那么如何访问这个 meta 字段:
      • 一个路由匹配到的所有路由记录会暴露为 $route 对象 (还有在导航守卫中的路由对象) 的 $route.matched 数组。因此,我们需要遍历 $route.matched 来检查路由记录中的 meta 字段。
  • 基于路由的动态过渡

    • 1
      2
      3
      4
      <!-- 使用动态的 transition name -->
      <transition :name="transitionName">
      <router-view></router-view>
      </transition>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    // 接着在父组件内
    // watch $route 决定使用哪种过渡
    watch: {
    '$route' (to, from) {
    const toDepth = to.path.split('/').length
    const fromDepth = from.path.split('/').length
    this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
    }
    }
  • 数据获取

    • 导航完成后获取数据: 当你使用这种方式时,我们会马上导航和渲染组件,然后在组件的 created 钩子中获取数据。这让我们有机会在数据获取期间展示一个 loading 状态,还可以在不同视图间展示不同的 loading 状态。
    • 在导航完成前获取数据: 通过这种方式,我们在导航转入新的路由前获取数据。我们可以在接下来的组件的 beforeRouteEnterbeforeRouteUpdate 守卫中获取数据,当数据获取成功后只调用 next 方法。具体请移步
  • 滚动行为

    • 注意 这个功能只在支持 history.pushState 的浏览器中可用。
    • 当创建一个 Router 实例,你可以提供一个 scrollBehavior 方法:

      1
      2
      3
      4
      5
      6
      const router = new VueRouter({
      routes: [...],
      scrollBehavior (to, from, savedPosition) {
      // return 期望滚动到哪个的位置
      }
      })
    • 对于所有路由导航,简单地让页面滚动到顶部。返回 savedPosition,在按下 后退/前进 按钮时,就会像浏览器的原生表现那样:

      1
      2
      3
      4
      5
      6
      7
      scrollBehavior (to, from, savedPosition) {
      if (savedPosition) {
      return savedPosition
      } else {
      return { x: 0, y: 0 }
      }
      }
    • 异步滚动: 你也可以返回一个 Promise 来得出预期的位置描述.

      1
      2
      3
      4
      5
      6
      7
      scrollBehavior (to, from, savedPosition) {
      return new Promise((resolve, reject) => {
      setTimeout(() => {
      resolve({ x: 0, y: 0 })
      }, 500)
      })
      }
  • Vue-Router导航守卫

    • 全局守卫
      • router.beforeEach 全局前置守卫 进入路由之前.
      • router.beforeResolve 全局解析守卫(2.5.0+) 在beforeRouteEnter调用之后调用
      • router.afterEach 全局后置钩子 进入路由之后
    • 路由独享守卫
      • beforeEnter()
    • 组件内守卫
    • beforeRouteEnter() 进入路由前
    • beforeRouteUpdate() (2.2) 路由复用同一个组件时
    • beforeRouteLeave() 离开当前路由时