将一个对象添加到对象数组vuetify模型中



我正在尝试保存动态加载到对象数组中的单选按钮的值。Thoose收音机是一系列形式问题的选项,我想得到这样的东西:

[{"question1":{
"selected": <id>,
...
},...]

但我不知道该如何定义数据,也不知道如何使用无线电组的v-model属性来引用它。

这是我最好的尝试:

<v-radio-group v-model="answers[question.question_id]">
<v-row justify="center">
<v-col v-for="option in question.options" :key="option.option_id">
<v-radio
:label="option.option_text"
:name="question.question_id"
:value="option.option_id"                      
></v-radio>
</v-col>
</v-row>
</v-radio-group>

数据:

data: () => ({
...
answers: [],
...
}),

我从中得到的是:[anwswer_id1, anwswer_id1...],女巫很近,但并不完全是我需要的

一个简单的方法可以是这样的:

<template>
<v-layout column>
<v-radio-group v-model="questions[questionIndex][currentQuestionId].selected">
<v-row justify="center">
<v-col v-for="(option,i) in questions[questionIndex][currentQuestionId].options" :key="i">
<v-radio :label="option.text" :name="currentQuestionId" :value="option._id"></v-radio>
</v-col>
</v-row>
</v-radio-group>
<v-btn @click="handleClickButtonNext">next question</v-btn>
<v-btn @click="handleClickButtonPrev">previous question</v-btn>
</v-layout>
</template>
<script>
export default {
data() {
return {
questions: [
{
question0: {
selected: null,
options: [
{
text: "text 1",
_id: 1
},
{
text: "text 2",
_id: 2
},
{
text: "text 3",
_id: 3
}
]
}
},
{
question1: {
selected: null,
options: [
{
text: "text 2",
_id: 2
},
{
text: "text 3",
_id: 3
},
{
text: "text 4",
_id: 4
}
]
}
},
],
questionIndex: 0
};
},
computed: {
currentQuestionId() {
return "question" + this.questionIndex;
}
},
methods: {
handleClickButtonNext() {
if (this.questionIndex < this.questions.length-1) this.questionIndex++;
},
handleClickButtonPrev() {
if (this.questionIndex > 0) this.questionIndex--;
},
}
};
</script>

其中:questionIndex-跟踪当前问题索引currentQuestionId-为您提供当前问题idhandleClickButtonNext / handleClickButtonPrev-让您在问题之间跳转

如果你只想一次显示一个问题,这是一种方法。

否则,您还可以摆脱对索引的跟踪,并循环问题数组:

<template>
<v-layout column>
<v-radio-group
v-for="(question, j) in questions"
:key="j"
v-model="question[`question${j}`].selected"
>
<v-row justify="center">
<v-col v-for="(option,i) in question[`question${j}`].options" :key="i">
<v-radio :label="option.text" :name="`question${j}`" :value="option._id"></v-radio>
</v-col>
</v-row>
</v-radio-group>
</v-layout>
</template>
<script>
export default {
data() {
return {
questions: [
{
question0: {
selected: null,
options: [
{
text: "text 1",
_id: 1
},
{
text: "text 2",
_id: 2
},
{
text: "text 3",
_id: 3
}
]
}
},
{
question1: {
selected: null,
options: [
{
text: "text 2",
_id: 2
},
{
text: "text 3",
_id: 3
},
{
text: "text 4",
_id: 4
}
]
}
}
]
};
}
};
</script>

最新更新