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

问题描述 投票:0回答:1

我目前只在我尝试编辑表单时收到[vuex] Do not mutate vuex store state outside mutation handlers错误,如果我发布一个新的插件,它工作正常。从this doc我不知道我哪里出错 - 当我从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和本地州处理方式的理解是有缺陷的

javascript vue.js vuex
1个回答
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 } 
    }
  }
}

有一个很好的包裹将为你做最多的工作:https://github.com/maoberlehner/vuex-map-fields。您可以使用它来半自动生成使用每个字段的getter和setter进行计算。

© www.soinside.com 2019 - 2024. All rights reserved.