Vue JS表单问题-在处理程序外部更改Vuex存储状态

时间:2018-09-11 09:02:01

标签: javascript vue.js vuex

当前,仅当我尝试编辑表单时才出现[vuex] Do not mutate vuex store state outside mutation handlers错误,如果我要发布新的插件,则可以正常工作。从this文档中,我不确定哪里出了问题-当我从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和本地状态处理方式的理解是有缺陷的

1 个答案:

答案 0 :(得分:2)

由于直接编辑状态而收到此错误。

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 } 
    }
  }
}

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