vue.js - 在 vuex 中直接改变状态
问题描述
我真的没有在动作中设置状态的缺点。好的突变对 vue-devtools 有用,但还有其他用处吗?是否有任何代码示例来显示障碍?
解决方案
有一个更好的方法可以做到这一点:
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中设置状态。
推荐阅读
- html - 响应列容器
- python - 链表错误:'int' 对象没有属性 'next'
- flutter - FutureProvider:如何使用 catchError 构建错误屏幕
- c++ - 将opencv矩形坐标转换为yolo对象坐标进行图像标注
- excel - 使用 Excel 名称管理器时如何忽略动态范围中的空白
- javascript - 在不使用任何第三方状态管理库的情况下,在反应中创建自定义钩子状态并从任何地方操纵全局状态
- c++ - c ++如何使用fstream修改文件
- sql-server - SQL Server 日期在 Analysis Services 中转换为日期/时间
- angular - 使用对象的角度图
- ibm-cloud - FAILED 插件“dev”已在 IBM Cloud CLI 中使用