Используйте индекс в v-for
для изменений v-модели, чтобы он изменял свойства объекта вопроса, а не их экземпляр:
new Vue({
el: '#app',
data () {
return {
//question_1: '', //don't need question_1, 2 and 3
// question_2: '',
// question_3: '',
questions: [
{ question: 'Question 1', variable: 'no'}, //notice that I have stored default values in question. Also consider renaming variable to answer to preserve good semantics.
{ question: 'Question 2', variable: 'yes'},
{ question: 'Question 3', variable: 'no'},
]
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div id="radioButtons">
<div v-for="(question_obj, index) in questions" :key="index" class="form-group form-radio">
<span>{{ question_obj.question }} {{ question_obj.variable }}</span>
<br>
<label>
<input type="radio" :name="'question-' + index" v-model="questions[index].variable" value="yes" :checked="question_obj.variable == 'yes'">
<span>Yes</span>
</label>
<label>
<input type="radio" :name="'question-' + index" v-model="questions[index].variable" value="no" :checked="question_obj.variable == 'no'">
<span>No</span>
</label>
</div>
</div>
</div>
Примечание: Нет необходимости хранить ответы в вопросах_1, вопрос_2, вопрос_3, поскольку у вас может быть более 3 вопросов, иэто не будет эффективным.Лучше всего хранить ответ в значении переменной свойства.
Итак, в компоненте это будет выглядеть так:
<template>
<div id="radioButtons">
<div v-for="(question_obj, index) in questions" :key="index" class="form-group form-radio">
<span>{{ question_obj.question }} {{ question_obj.variable }}</span>
<br>
<label>
<input type="radio" :name="'question-' + index" v-model="questions[index].variable" value="yes" :checked="question_obj.variable == 'yes'">
<span>Yes</span>
</label>
<label>
<input type="radio" :name="'question-' + index" v-model="questions[index].variable" value="no" :checked="question_obj.variable == 'no'">
<span>No</span>
</label>
</div>
</div>
</template>
<script>
export default {
name: 'radioButtons',
data () {
return {
//question_1: '', //don't need question_1, 2 and 3
// question_2: '',
// question_3: '',
questions: [
{ question: 'Question 1', variable: 'no'}, //notice that I have stored default values in question. Also consider renaming variable to answer to preserve good semantics.
{ question: 'Question 2', variable: 'yes'},
{ question: 'Question 3', variable: 'no'},
]
}
},
}
</script>
<style>
</style>