我们知道,为了对同一组件中的params更改做出反应,我们使用 beforeRouteUpdate
hook或者观察 $route
.
watching $route:
const User = {
template: '...',
watch: {
'$route' (to, from) {
// react to route changes...
}
}
}
beforeRouteUpdate Method:
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
next()
}
}
这两者有什么区别?如果两者相同那么为什么vue路由器介绍 beforeRouteUpdate
?
2 回答
来自documentation
beforeRouteUpdate
:无可否认,文档在
$route
对象的值实际发生变化之前调用了钩子 . 这是导航钩子和在$route
上设置观察者之间的区别,它将在$route
的值发生变化后被调用 .使用
beforeRouteUpdate
导航防护,您可以确定是否要阻止路径更改(通过不调用next()
)或完全转到其他路径(通过传递不同的路径值,如next('/foo')
,next({ name: 'foo' })
等) .这是一个示例fiddle,显示何时调用这些函数 .
正如@thanksd所说
beforeRouteUpdate
就像守卫 . 通过观察,您无法阻止路线采取行动,但使用beforeRouteUpdate
可以使用next
功能 . 例如,您可以等待,直到您的数据被提取,然后继续到组件 .您可以在vue-router文档Data Fetching中找到更多信息 .