So i am using Vuex and have a simple mutation set up which console logs a message. I have two routes setup, the /
which goes to my HelloWorld component and /another
which goes to the AnotherWorld component. I am trying to setup a watch
on my route
so that when the route changes, it fires off the mutation. I did setup a watch
but it doesn't seem to be firing off my mutation.
Check out this CodeSandbox.
查看代码段:
这是我的Vuex商店:-
mutations: {
routeChange() {
console.log("Helloooo!!!!!");
}
这是“我的世界”组件:
<template>
<div>
<h1>Hello World!!!</h1>
<router-link to="/another">Switch</router-link>
</div>
</template>
<script>
export default {
name: "HelloWorld",
watch: {
$route(to, from) {
this.$store.commit("routeChange");
}
}
};
</script>
这是我的AnotherWorld组件:-
<template>
<div>
<h1>Another World</h1>
<router-link to="/">Back</router-link>
</div>
</template>
<script>
export default {};
</script>
如您所见,我已经设置了手表,但是它似乎没有做任何事情。任何帮助将不胜感激。谢谢。
如果将观察者放在单独的路由组件中,它们将永远不会触发,因为$ route在这些组件实例化之前设置,然后在这些组件销毁之后更改。
You either need to put the watch in App.vue (parent of
<router-view>
), or commit from one of the vue-router guards (https://router.vuejs.org/guide/advanced/navigation-guards.html)I would instead use a global after hook navigation guard in your router.
例如