首页 > 解决方案 > 如何提交应该在同一个 Vuex Store 对象中并且未映射到 store 对象的多个嵌套值?

问题描述

如果我想在 Vuex 存储中提交输入值和选定的选项(没有“标签”字符串,以便我发送的对象与我的 Vuex 存储对象匹配),它将如何工作?

模板

                <div v-for="(section, indexSections) in sections" :key="indexSections">                                
                    <div v-for="(item, indexItem) in section" :key="indexItem">                      
                      <div>

                        <select
                          v-model="sections[indexSection][indexItem].options"                        
                          :options="selectOptions"
                        ></select>

                        <b-input
                          type="text"
                          v-model="sections[indexSection][indexItem].sectionItem"                                                   
                        ></b-input>
                        <b-button @click="removeItem({section,item})"/>  

                      </div>
                    </div>      

                  <div">
                    <b-button @click="addNewItem(section)"/>                                        
                    <b-button @click="addNewSection"/>
                  </div>

                </div>

数据

selectOptions: [
        {
          options: { option1: true, option2: true },
          label: "First"
        },
        {
          options: { option1: false, option2: true },
          label: "Second"
        }      
      ]

计算

Computed: {

sections: {
      get() {
        return this.$store.state.sections;
      }
    }

店铺

sections: [
                [{
                    sectionItem: "",
                    options: {
                        strict: true,
                        includes: true
                    }

                }]
            ],

标签: jsonvue.jsnestedvuexv-model

解决方案


您不能使用v-model它来更改 Vuex 状态,这就是突变的用途。

v-model只是语法糖并处理事件和值的更新。您必须v-on:change自己实现并调用 Vuex 突变来设置所选选项。

您的selectOptions阵列看起来不寻常。通常你只有 alabel和 a valuefor 选项。value是用户选择选项时的选定值。

<template>
    <div>
        <select @change="onChange">
            <option v-for="option in selectOptions" :value="option.value">
                {{ option.label }}
            </option>
        </select>
    </div>
</template>

<script>
export default {
    data () {
        return {
            selectOptions: [
                //...
            ],
        }
    },
    methods: {
        onChange(event) {
            this.$store.commit('setSelectedOption', event.target.value);
        },
    },
};
</script>

推荐阅读