首页 > 解决方案 > 在 vuex 中直接改变状态

问题描述

我真的没有在动作中设置状态的缺点。好的突变对 vue-devtools 有用,但还有其他用处吗?是否有任何代码示例来显示障碍?

标签: vue.jsstatevuexaction

解决方案


有一个更好的方法可以做到这一点:

Actions 允许进行异步调用,这意味着您可以进行 https 请求、等待、应答和提交(调用突变)。

突变是同步的,因为这里是更新状态的地方。

因此,如果您不需要异步调用,则可以直接从组件调用突变:

// Using this.$store.commit()    
// some component
...
methods: {
  callAMutation() {
    const someValue = "Update the vuex state with this";
    // call the mutation without call an action
    this.$store.commit("theMutationName", somevalue);
    // if the store is using modules
    // this.$store.commit("moduleName/theMutationName", somevalue);
  }    
}
...

现在使用{ mapMutations }

// some component
<script>
import { mapMutations } from 'vuex';
...
methods: {
  ...mapMutations(["theMutationName"]), 
  // again, if you have a store with modules, use the next format
  // ...mapMutations({ aModuleMutation: "moduleName/theMutationName"})
  callAMutation() {
    const someValue = "Update the vuex state with this";
    // call the mutation without call an action
    // call the mutation ["theMutationName"] as a method
    this.theMutationName(somevalue);
    // if the store is using modules, call the mutation as a method
    // this.aModuleMutation(somevalue);
  }    
}
...
</script>

这样可以减少代码编写代码,因为该操作不是必需的,并且对于在使用商店的组件之间共享代码很有用。

之所以有突变是因为:现代状态管理工具的驱动要求之一是可追溯性[ https://blog.logrocket.com/vuex-showdown-mutations-vs-actions-f48f2f7df54b/],突变允许知道在哪里,状态如何以及何时发生变化,这样您就可以跟踪哪个组件正在调用某些操作或突变,调试大型应用程序可能会很痛苦。

但是...在vue精通课程中,我听到Damian Dulisz说mutation和actions会合并,如果是的话,你会直接在actions中设置状态。


推荐阅读