简体   繁体   English

在路由更改 VueJS 上运行突变?

[英]Run mutation on Route change VueJS?

So i am using Vuex and have a simple mutation set up which console logs a message.所以我正在使用 Vuex 并设置了一个简单的突变设置,该控制台记录一条消息。 I have two routes setup, the / which goes to my HelloWorld component and /another which goes to the AnotherWorld component.我有两个路由设置, /去我的 HelloWorld 组件和/another去另一个世界组件。 I am trying to setup a watch on my route so that when the route changes, it fires off the mutation.我正在尝试在我的route上设置一个watch ,以便当路线改变时,它会触发突变。 I did setup a watch but it doesn't seem to be firing off my mutation.我确实设置了一块watch ,但它似乎并没有触发我的突变。

Check out this CodeSandbox .看看这个CodeSandbox

Check out the code snippet:-查看代码片段:-

This is My Vuex Store:-这是我的 Vuex 商店:-

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

This is My Hello World Component:-这是我的 Hello World 组件:-

<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.谢谢你。

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.如果您将观察者放在单个路由组件中,它们将永远不会触发,因为 $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 )您要么需要将手表放在 App.vue ( <router-view>父级)中,要么从 vue-router 保护之一( https://router.vuejs.org/guide/advanced/navigation-guards 提交。 html )

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如果您只想捕获远离某些组件的路线导航,您可以使用组件内的beforeRouteLeave 保护

// MyComponent.vue

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM