当使用路由参数时,例如从 /user/foo
导航到 /user/bar
,原来的组件实例会被复用。因为两个路由都渲染同个组件,比起销毁再创建,复用则显得更加高效。不过,这也意味着组件的生命周期钩子不会再被调用。那如果我们要在组件中监听路由参数的变化,就只能通过watch (监测变化) $route
对象,或使用 beforeRouteUpdate
的组件内守卫。
方式一: 监听 $route
const User = {
template: '...',
watch: {
$route(to, from) {
// 对路由变化作出响应...
}
}
}
方式二:通过组件内的导航守卫,beforeRouteUpdate ,(和created(){}生命周期函数同级别)
const User = {
template: '...',
beforeRouteUpdate(to, from, next) {
// react to route changes...
// don't forget to call next()
}
}