假如我们有多个路由地址,如下:
# 其中,100 和 200 是用户ID /user/100 /user/200
上面的路由地址均被 User.vue 组件进行渲染。当我们的路由路径参数由100变为200的时候,我们需要作出相应的动作。
当使用路由参数时,例如从 /user/100 导航到 /user/200,原来的组件实例会被复用。因为两个路由都渲染同个组件User,比起销毁再创建,复用则显得更加高效。不过,这也意味着组件的生命周期钩子不会再被调用。
复用组件时,想对路由参数的变化作出响应的话,你可以简单地 watch (监测变化) $route 对象:
<template>
<div class="user">
<h2>User Page</h2>
<p>id = {{ this.$route.params.id }}</p>
</div>
</template>
<script>
export default {
name: "User",
watch: {
'$route'(to, from) {
// 对路由变化作出响应
console.debug(to)
}
}
}
</script>
<style scoped>
</style>或者使用 2.2 中引入的 beforeRouteUpdate 导航守卫:
<template>
<div class="user">
<h2>User Page</h2>
<p>id = {{ this.$route.params.id }}</p>
</div>
</template>
<script>
export default {
name: "User",
beforeRouteUpdate: function(to, from, next){
// 对路由的变化作出响应
// 不要忘记调用next()函数
console.debug("路由参数变化了...")
// 如果忘记了调用next()方法,则组件视图不会被渲染(不可见)
next()
}
}
</script>
<style scoped></style>总结:
本文介绍了怎样去监听路由参数的变化,可以通过两种方式,分别为:
使用 watch 监听 $route 对象
使用 beforeRouteUpdate 钩子函数