为什么调用组件方法修改数据时,我的Vuex store state会同步变化?
问题根因
这个问题是引用类型浅拷贝导致的:
this.currentApp.stacks是Vuex中存储的数组,属于引用类型数据- 你在created生命周期直接执行
this.updated.app_stacks = this.currentApp.stacks时,只是把数组的内存地址赋值给了组件的data属性,两者实际上指向同一个数组 - 后续你对
this.updated.app_stacks执行push、splice等操作时,本质就是在修改Vuex里的原数组
修复方案
只需要在给updated.app_stacks赋值的时候做一次数组拷贝即可,把created里的对应赋值代码改成:
// 数组元素都是基本类型字符串,浅拷贝就足够使用 this.updated.app_stacks = [...this.currentApp.stacks] // 也可以用slice方法实现:this.updated.app_stacks = this.currentApp.stacks.slice() // 如果后续数组有嵌套对象的需求,可以用JSON序列化实现深拷贝:this.updated.app_stacks = JSON.parse(JSON.stringify(this.currentApp.stacks))
额外优化建议
- 你当前data中
updated对象的app_stacks初始值设为了空字符串,但实际使用时是数组类型,建议把初始值改成空数组避免后续触发类型错误:
updated: { app_name: "", app_subtitle: "", app_description: "", app_url: "", app_category: "", app_stacks: [], // 改为空数组 stackTech: "", },
- 你给
currentApp赋值的时候也是直接取的Vuex里的引用,如果不需要修改currentApp的话,也建议做一次对象拷贝避免误改Vuex数据:
this.currentApp = {...this.$store.state.your_apps[this.$route.params.index]}
内容的提问来源于stack exchange,提问作者Tazim Rahbar
相关产品推荐
相关产品推荐

