beforeRouteUpdate导航守卫使用注意

前言

在使用 vue-router 的组件内的守卫 beforeRouteUpdate (2.2 新增)时,需要注意组件内守卫获取路由参数的时机。
beforeRouteUpdate 当组件内子路由发生变化时,会出发该导航守卫。

环境

  • vue 2.5.2
  • element-ui: 2.6.1

效果

当路由更新之后,可以从 this.$route 中获取到 params 中的参数。
在这里插入图片描述

代码

index.vue

<template>
  <section>
    <el-button size="mini" @click="toA">A组件</el-button>
    <el-button type="primary" size="mini" @click="toB">B组件</el-button>
    <router-view />
  </section>
</template>

<script>
export default {
  beforeRouteUpdate (to, from, next) {
    console.log('路由更新之前:从to获取参数', to.params, '从this.$route获取参数', this.$route.params)
    next()
    console.log('路由更新之后:从to获取参数', to.params, '从this.$route获取参数', this.$route.params)
  },
  methods: {
    toA () {
      this.$router.push({
        path: '/index/a/wj'
      })
    },
    toB () {
      this.$router.push({
        path: '/index/b',
        query: {
          name: 'jj'
        }
      })
    }
  }
}
</script>

a.vue

<template>
  <section>
    组件A
  </section>
</template>

b.vue

<template>
  <section>
    组件B
  </section>
</template>

router

export default new Router({
  routes: [
    {
      path: '/index',
      name: 'index',
      component: Index,
      children: [
        {
          path: 'a/:name',
          name: 'a',
          component: A
        },
        {
          path: 'b',
          name: 'b',
          component: B
        }
      ]
    },
  ]
})

总结

当使用 beforeRouteUpdate 导航守卫时,应该等 next() 函数执行后,再获取 paramsquery 中的参数。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章