我正在尝试为测验创建问题添加器。每个问题都有答案,其中包含ID:
var questions = [
{
question: "1+1 is",
answers: [
{ id: 0, answer: "1", correct: false },
{ id: 1, answer: "0", correct: false },
{ id: 2, answer: "2", correct: false }
],
correct: [2],
selected: [],
false: [0, 1]
}]
但是我不知道如何创建带有ID的对象数组。我知道answercorrect
,answerfalse1
/ 2
是错误的,但是我该怎么办?
一些HTML:
<label>Otázka: <input v-model="question" type="text"></label><br><br>
<label>Správná odpověď: <input v-model="answercorrect" type="text"></label><br><br>
<label>Odpověď: <input v-model="answerfalse" type="text"></label><br><br>
<label>Odpověď: <input v-model="answerfalse2" type="text"></label>
JS:
addQuestion()
{
if (this.question != "")
{
this.questions.push(this.question);
this.question = "";
this.questions.push(this.answers[this.answercorrect, this.answerfalse, this.answerfalse2]);
this.answercorrect = "";
this.answerfalse = "";
this.answerfalse2 = "";
}
}
答案 0 :(得分:0)
我将创建一个函数,该函数生成一个空白的问题对象,其中包含一组生成的答案对象。
let answerId = 0;
let questionId = 0;
const createAnswer = () => ({ id: answerId++, answer: '', correct: false })
const createQuestion = () => ({
id: questionId++,
question: '',
answers: [createAnswer()],
})
组件将使用这些功能添加新的问题和答案:
export default {
data() {
return {
questions: [createQuestion()],
};
},
methods: {
addQuestion() {
this.questions.push(createQuestion())
},
addAnswer(q) {
/**
* Since the `answers` object is part of the `questions` object,
* this takes a question as an argument, and adds a new `answer`
* object to its `answers` array.
*/
q.answers.push(createAnswer())
},
},
}
在模板中,使用v-for
渲染questions
,然后使用v-on
button-click handlers绑定到组件的addQuestion()
和addAnswer()
:
<template>
<div>
<button @click="addQuestion">Add question</button>
<fieldset class="question" v-for="q in questions" :key="q.id">
<legend>Question: <input v-model="q.question" type="text" /></legend>
<button @click="addAnswer(q)">Add answer</button>
<label class="answer" v-for="answer in q.answers" :key="answer.id">
Answer: <input type="text" v-model="answer.answer" />
Correct: <input type="checkbox" v-model="answer.correct" />
</label>
</fieldset>
</div>
</template>