前言
在使用 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()
函數執行後,再獲取 params
或 query
中的參數。