In my Vue 3 setup, I have a Vuex store with an array in the state:
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;
},
},
});
I also have a component that is supposed to display a list of checkboxes corresponding to the "questions" array in the state.
<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>
While trying to achieve two-way binding using v-model for each input element in the list, it seems that accessing specific computeds with an index in the template is not working as expected. Although there are no errors thrown, the binding between the checkbox value and the .value
property in the question objects is not functioning correctly. Is my approach incorrect here? Can arrays of "computed" properties be created using .map()
? Is there any way to utilize v-model with this particular data structure?