Vue JS 表单问题 - 在处理程序之外改变 vuex 存储状态



我目前仅在尝试编辑表单时才收到[vuex] Do not mutate vuex store state outside mutation handlers错误,如果我发布新插件,它可以正常工作。从这个文档中,我不确定我哪里出了问题 - 当我从 vuex 获取插件时,我尝试为本地状态提供这些值,然后不理会 vuex。理想情况下,一旦获取了 vuex,在提交表单之前,我不需要再次触摸它。但我不确定究竟是什么导致了错误

<template>
<div>
<h4>{{this.$route.query.mode==="new"?"New":"Edit"}} Plugin</h4>
<form class="">
<label>Id</label>
<input :value="plugin.id" class="" type="text" @input="updateId">
<label>Name</label>
<input :value="plugin.name" class="" type="text" @input="updateName">
<label>Description</label>
<textarea :value="plugin.description" class="" type="text" @input="updateDescription"></textarea>
<label>Version</label>
<input :value="plugin.version" class="" type="text" @input="updateVersion">
<button type="submit" @click.prevent="submitForm">Submit</button>
</form>
</div>
</template>
<script>
import util from '~/assets/js/util'
export default {
created() {
if (this.mode === 'edit') {
this.plugin = this.$store.state.currentLicence.associatedPlugins.find(p => p.pluginId === this.$route.query.pluginId)
}
},
methods: {
updateId(v) {
this.plugin.id = v.target.value
},
updateName(v) {
this.plugin.name = v.target.value
},
updateDescription(v) {
this.plugin.description = v.target.value
},
updateVersion(v) {
this.plugin.version = v.target.value
}
},
computed: {
mode() { return this.$route.query.mode }
},
data: () => ({
plugin: {
id: null,
name: null,
description: null,
version: null
}
})
}
</script>

感谢您的任何帮助,显然我对 vuex 和当地状态处理方式的理解是有缺陷的

您收到此错误是因为您直接编辑状态。

this.plugin = this.$store.state.currentLicence.associatedPlugins.find(p => p.pluginId === this.$route.query.pluginId)- 这正是代码的这一部分,您将存储中的对象直接放入数据中,因此通过编辑字段,您可以直接编辑状态。别这样!

你应该总是使用这样的东西(我不确定嵌套计算将如何工作,但我认为你不必嵌套它(:

computed: {
plugin: {
id: {
get () { // get it from store }
set (value) { // dispatch the mutation with the new data } 
}
}
}

有一个很好的软件包,可以为您完成大部分工作:https://github.com/maoberlehner/vuex-map-fields。您可以使用它来半自动生成每个字段的 getter 和 setter 计算。

最新更新