繁体   English   中英

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

[英]Run mutation on Route change VueJS?

所以我正在使用 Vuex 并设置了一个简单的突变设置,该控制台记录一条消息。 我有两个路由设置, /去我的 HelloWorld 组件和/another去另一个世界组件。 我正在尝试在我的route上设置一个watch ,以便当路线改变时,它会触发突变。 我确实设置了一块watch ,但它似乎并没有触发我的突变。

看看这个CodeSandbox

查看代码片段:-

这是我的 Vuex 商店:-

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

这是我的 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>

这是我的另一个世界组件:-

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

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

如您所见,我已经设置了手表,但它似乎没有做任何事情。 任何帮助将不胜感激。 谢谢你。

如果您将观察者放在单个路由组件中,它们将永远不会触发,因为 $route 在这些组件实例化之前设置,然后在这些组件销毁后更改。

您要么需要将手表放在 App.vue ( <router-view>父级)中,要么从 vue-router 保护之一( https://router.vuejs.org/guide/advanced/navigation-guards 提交。 html )

我会在您的路由器中使用全局后挂钩导航防护。

例如

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

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