Muk*_*mar 11 vue.js vue-router vuejs2
我们知道,为了对同一组件中的params变化作出反应,我们使用beforeRouteUpdate钩子或观察$route.
看$ route:
const User = {
template: '...',
watch: {
'$route' (to, from) {
// react to route changes...
}
}
}
Run Code Online (Sandbox Code Playgroud)
beforeRouteUpdate方法:
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
next()
}
}
Run Code Online (Sandbox Code Playgroud)
这两者有什么区别?如果两者相同那么为什么vue路由器介绍beforeRouteUpdate?
tha*_*ksd 12
从文档上beforeRouteUpdate:
在呈现此组件的路由已更改时调用,但此组件在新路由中重用.例如,对于具有动态参数的路径
/foo/:id,当我们在/foo/1和之间导航时/foo/2,Foo将重用相同的组件实例,并且当发生这种情况时将调用此挂钩.
无可否认,文档在对象的值实际发生变化之前被调用$route.这是导航钩子和设置观察者之间的区别$route,它将在值发生变化后被调用$route.
使用beforeRouteUpdate导航后卫,你可以决定你是否要阻止路线更改(不是通过调用next()),或者去一个完全不同的路线(通过传递不同的路线类似的值next('/foo'),next({ name: 'foo' })等等).
这是一个示例小提琴,显示何时调用这些函数.