正如我们所知,为了对同一组件中的参数更改使用react,我们使用 beforeRouteUpdate
Hook 或观察 $route
。
正在观看 $route:
const User = {
template: '...',
watch: {
'$route' (to, from) {
// react to route changes...
}
}
}
beforeRouteUpdate 方法:
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
next()
}
}
这两者有什么区别?如果两者相同那么为什么 vue router 引入了 beforeRouteUpdate
?
最佳答案
来自documentation在 beforeRouteUpdate
上:
called when the route that renders this component has changed, but this component is reused in the new route. For example, given a route with params
/users/:id
, when we navigate between/users/1
and/users/2
, the sameUserDetails
component instance will be reused, and this hook will be called when that happens. Because the component is mounted while this happens, the navigation guard has access tothis
component instance.
诚然,文档并不清楚钩子(Hook)是在 $route
对象的值实际改变之前被调用的。这就是此导航 Hook 与在 $route
上设置观察者之间的区别,$route
的值发生更改后将被调用。
使用 beforeRouteUpdate
导航守卫,您可以确定是否要阻止路由更改(通过不调用 next()
)或转到不同的路径完全路由(通过传递不同的路由值,如 next('/foo')
、next({ name: 'foo' })
等)。
这是一个例子 fiddle显示这些函数何时被调用。
关于vue.js - beforeRouteUpdate 和 watching '$route' - Vue.js 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47184331/