首页 > 解决方案 > Vuex v-model 到对象状态字段

问题描述

我有一个 Vuex 状态,像这样(它也有一个 getter,名为configs

configs: {

    1303401: {

        exampleValue: 'test'

    }

}

我还有一个输入,我在其中exampleValue对 Vuex 商店的状态进行 v 建模:

<input type="text" v-model="config.exampleValue" />

这是我用来返回的计算属性config

config: {

    get () {

        return this.$store.getters.configs[1303401]

    },
    set (value) {

        //this should set the configs[1303401] field with the updated exampleValue
        this.$store.dispatch('UPDATE_CONFIG', value)

    }


}

输入的值变为 的值config.exampleValue,因此计算的数据不是未定义的,但 Vuex 状态不会更新。

此外,如果我尝试console.log设置设置器中的值,控制台中不会出现任何内容,因此设置器甚至不会执行

这可能是因为它没有设置config计算​​属性,config.exampleValue但是我不知道如何处理它。

正如上面提到的@asi-ple,将get更改为returnconfigs[1303401].exampleValue会起作用,但问题是,配置有更多字段,页面有更多输入,我需要以这种方式为所有字段创建一个计算属性.

标签: javascriptvue.jsvuex

解决方案


实际上,如果你有多个字段,你可以在这里做一些逻辑。

可以说你有

configs: {
    1303401: {
        exampleValue: 'test',
        exampleValue2: 'test2',
        exampleValue3: 'test3',
        ...
    } 
}

比您应该将模板更改为:

<input type="text" :value="config[1303401].exampleValue1" @input="update_config($event, 'exampleValue1')" />
<input type="text" :value="config[1303401].exampleValue2" @input="update_config($event, 'exampleValue2')" />
<input type="text" :value="config[1303401].exampleValue3" @input="update_config($event, 'exampleValue3')" />

而你的方法是这样的

methods:{
    update_config($event, where){
          this.$store.commit("UPDATE_CONFIG", {value: $event.target.data, where: where})
    }
}

然后你的突变处理程序看起来像这个

UPDATE_CONFIG(state, payload){
       state.configs[1303401][payload.where] = payload.value
}

基本上上面的代码,你在你的状态下制作一个配置数据,它应该在你的模板中使用双向数据绑定。然后你正在创建你的输入 :value 像 get 方法一样工作,@input 监听器像 set 方法一样工作,然后 update_config 正在提交你的更改和突变处理程序将它们设置在正确的位置


推荐阅读