赛前更新和观看之间的区别'$路线';-Vue.js?
正如我们所知,为了对同一组件中的参数变化作出反应,我们在路由更新之前使用赛前更新和观看之间的区别'$路线';-Vue.js?,vue.js,vuejs2,vue-router,Vue.js,Vuejs2,Vue Router,正如我们所知,为了对同一组件中的参数变化作出反应,我们在路由更新之前使用钩住或观看$route 观看$route: const User = { template: '...', watch: { '$route' (to, from) { // react to route changes... } } } const User = { template: '...', beforeRouteUpdate (to, from, next) {
钩住或观看$route
观看$route:
const User = {
template: '...',
watch: {
'$route' (to, from) {
// react to route changes...
}
}
}
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
next()
}
}
路由前更新方法:
const User = {
template: '...',
watch: {
'$route' (to, from) {
// react to route changes...
}
}
}
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
next()
}
}
这两者有什么区别?如果两者都相同,那么为什么vue路由器在路由更新之前引入了
当呈现此组件的路由已更改,但此组件在新路由中被重用时调用。例如,对于具有动态参数的路由/foo/:id
,当我们在/foo/1
和/foo/2
之间导航时,将重用相同的foo
组件实例,并在发生这种情况时调用此挂钩
无可否认,文档不清楚钩子是在$route
对象的值实际更改之前被调用的。这就是此导航挂钩与在$route
上设置观察者之间的区别,在$route
的值更改后将调用该观察者
使用beforeRouteUpdate
导航卫士,您可以确定是否要阻止路由更改(通过不调用next()
)或完全转到不同的路由(通过传递不同的路由值,如next('/foo')
,next({name:'foo'})
)
下面是一个示例,显示了调用这些函数的时间。正如@thanksd所说,$route
类似于guard。通过监视,您无法阻止路由执行操作,但通过beforeRouteUpdate
可以使用next
功能执行操作。例如,您可以等待直到提取数据,然后继续处理组件
您可以在vue路由器文档中找到更多信息。只有更改id才能重用/foo/:id
组件;但是/foo/1
和/foo
不是同一个组件!此外,$route
即使各个组件的路由(但子组件的路由)没有更改,也会运行watcherbeforeRouteUpdate
仅特定于当前组件。