如您所想,有几种方法可以满足您的要求。
1。 Vue-Router 钩子
当您导航到路由组件(您在 <router-view> 中渲染的组件)时,这些组件将具有您可以使用的特殊路由器生命周期挂钩:
beforeRouteEnter (to, from, next) {
getPost(to.params.id, (err, post) => {
next(vm => vm.setData(err, post))
})
},
// when route changes and this component is already rendered,
// the logic will be slightly different.
beforeRouteUpdate (to, from, next) {
this.post = null
getPost(to.params.id, (err, post) => {
this.setData(err, post)
next()
})
},
更多详情请关注官方documentation
2。 Vue-Router 导航守卫
您还可以使用导航守卫 - 在路线导航期间的某个时间点调用的函数:
router.beforeEach((to, from, next) => {
// ...
})
更多关于这个也可以在官方documentation
3。显式的、特定于组件的操作
当然,您也可以在组件本身中触发您想要的所有更改。在您导航到的组件中,或者在您的<router-view> 的根组件中。我的第一个想法是处理watcher 中的逻辑:
watch: {
$route: {
immediate: true, // also trigger handler on initial value
handler(newRoute) {
if (newRoute.params.myParam === 'my-param') {
document.body.classList.add('my-class');
}
}
}
}
我个人会在根布局组件中查看route,因为我喜欢为业务逻辑/身份验证(而不是样式)保留导航守卫。