Vuex 中状态发生变化时如何调度操作?

Shu*_*ary 2 javascript vue.js

我希望在状态发生变化时在 vuex 中部署一些操作。我能想到的唯一方法是在该状态上放置一个观察者并从那里进行部署,但我不确定这是否是最好的方法。有没有更优雅的方法来做到这一点?

M U*_*M U 5

您应该使用 Vuex 插件。https://vuex.vuejs.org/guide/plugins.html

const myPlugin = store => {
  // called when the store is initialized
  store.subscribe((mutation, state) => {
    // called after every mutation.
    // The mutation comes in the format of `{ type, payload }`.
  })
}
Run Code Online (Sandbox Code Playgroud)

这是完成您所询问的此类事情的最佳且推荐的方式。

当你定义插件时,记得在商店中注册它!

const store = new Vuex.Store({
  // ...
  plugins: [myPlugin]
})
Run Code Online (Sandbox Code Playgroud)