Somethingwhatever
Somethingwhatever

Reputation: 1368

Run mutation on Route change VueJS?

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.

Check out the code snippet:-

This is My Vuex Store:-

  mutations: {
    routeChange() {
      console.log("Helloooo!!!!!");
    }

This is My Hello World Component:-

<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>

This is my AnotherWorld Component:-

<template>
  <div>
    <h1>Another World</h1>
    <router-link to="/">Back</router-link>
  </div>
</template>

<script>
export default {};
</script>

As you can see i have setup the watch but it doesn't seem to be doing anything. Any help will be appreciated. Thank you.

Upvotes: 1

Views: 1484

Answers (2)

Phil
Phil

Reputation: 164970

I would instead use a global after hook navigation guard in your router.

For example

// router.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [...]
})

router.afterEach(() => {
  store.commit('routeChange')
})

export default router

If you only want to catch route navigation away from certain components, you can use the beforeRouteLeave in-component guard

// MyComponent.vue

export default {
  name: 'MyComponent',
  beforeRouteLeave (to, from, next) {
    this.$store.commit('routeChange')
    next()
  }
}

Upvotes: 1

Renaud
Renaud

Reputation: 1300

If you put watchers in individual route components they will never fire because $route is set before these components instantiation and is then changed after these components destruction.

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)

Upvotes: 1

Related Questions