我真的不了解在行动中设置状态的缺点。好的,变异对于vue-devtools是有用的,但是还有其他的吗?有什么代码样本来显示障碍吗?
发布于 2020-06-08 15:34:33
有更好的方法来做到这一点:
操作允许异步调用,这意味着您可以执行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说突变和动作将被合并,如果是的话,您将直接在动作中设置状态。
https://stackoverflow.com/questions/62263148
复制相似问题