【发布时间】:2022-01-08 07:48:14
【问题描述】:
我在 Vue 3 中有以下设置。
将数组作为状态一部分的 vuex 存储:
const store = createStore({
state: {
questions: [
{ text: 'A', value: false },
{ text: 'B', value: false },
{ text: 'C', value: true },
],
},
mutations: {
updateQuestionValue(state, { index, value }) {
state.questions[index].value = value;
},
},
});
还有一个组件,它试图呈现一个复选框列表,该列表应该对应于 state 中的“questions”数组。
<template>
<div v-for="(question, index) in questions">
<label :for="'q'+index">{{question.text}}</label>
<input :id="'q'+index" v-model="questionComputeds[index]" type="checkbox" />
</div>
</template>
<script setup>
import { computed } from 'vue';
import { useStore } from 'vuex';
const store = useStore();
const questions = computed(() => store.state.questions);
const questionComputeds = store.state.questions.map((q, i) =>
computed({
get() {
return store.state.questions[i].value;
},
set(value) {
store.commit('updateQuestionValue', { index: i, value });
},
})
);
</script>
如您所见,我希望使用 v-model 为列表中的每个输入元素制定两种方式的绑定,但是因为我将 vuex 与数组一起使用,所以我想在我的计算中使用 get/set 选项属性并使用模板中的索引访问特定的计算。但是我发现这不起作用。它不会引发错误,但也无法将复选框的值绑定到我的问题对象中的 .value 道具。我对这里的策略完全不了解吗?你甚至可以像.map() 那样制作“计算”数组吗?有什么方法可以将 v-model 与这种数据结构一起使用?
【问题讨论】:
标签: javascript vue.js vuex vuejs3 v-model