gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:42:45 25 4
gpt4 key购买 nike

仅当我尝试编辑表单时,我当前才会收到 [vuex] Do not mutate vuex store state Outsidemutation 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 和本地状态处理方式的理解是有缺陷的

最佳答案

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

this.plugin = this.$store.state.currentLicence.linkedPlugins.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 的计算。

关于javascript - Vue JS 表单问题 - 在处理程序之外改变 vuex 存储状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52272355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com