There are several ways to do what you are asking, as you can imagine.
1. Vue-Router Hooks
When you navigate to route components (components you render inside <router-view>
) these components will have special router lifecycle-hooks you can use:
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()
})
},
More about this in the official documentation
2. Vue-Router navigation guards
You could also use navigation guards - a function that is called at a certain point during a route navigation:
router.beforeEach((to, from, next) => {
// ...
})
More about this also in the official documentation
3. Explicit, component-specific action
Of course, you can also trigger all changes you want in the components itself. Either in the components you navigate to - or a root component for your <router-view>
. My first idea would be to handle the logic in a 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');
}
}
}
}
I personally would watch the route
in a root layout-component as I like to keep naviation guards for business logic / authentication (not style).
beforeRouterEnter
andbeforeRouteLeave
? – xianshenglu