我正在使用 Vue 2 構建一個調查,我正在嘗試構建答案陣列并將其發送到名為Evaluation的父組件 ,如下所示:https : //pastebin.com/rLEUh56a
我有一個名為QuestionItem.vue的組件 ,它是Evaluation的子組件,如下所示:https : //pastebin.com/RFPgKs5Q
答案陣列需要像這樣才能發送到 API:
answers: [
{
questionId: "6a9ad778-aacf-4e60-9610-37a767700b9f",
questionOptionIds:[
"1bc35f6c-900a-4764-84ee-23531e46e638",
],
answer: null
},
{
questionId: "d1c3f4f0-9525-4e6e-bb81-599d84b5cb02f",
questionOptionIds:[],
answer: "answered value"
},
]
其中如果question.type是text,range,stars或faces將questionOptionIds需要為空和answer財產需要在回答值,但如果question.type是radio或check,答案物業需求為空和questionOptionIds財產需要在回答選項用戶選擇。
我不確定如何根據在 QuestionItem.vue 組件中輸入的每個答案構建這個陣列。
感謝您的時間,祝您有美好的一天!
uj5u.com熱心網友回復:
您不能像這樣在 QuestionItem 組件上使用 v-model 作為答案:
<QuestionItem
v-for="(question, index) in questions"
:key="index"
:question="question"
:index="questionIndex"
v-model="answers"
class="flex-none w-full"
/>
v-model 將獲取從 child 發出的輸入值并將其設定為 answers,在這種情況下這沒有意義,因為 answers 是每個答案的陣列,而不是一個單一的答案。
您將需要在父組件中有一個自定義事件處理程式。像這樣的東西:
// in Evaluation.vue methods
answerChanged(answer) {
// remove this answer if it's already in the array
answers = answers.filter(a=>a.questionId != answer.questionId);
// add the submitted answer
answers.push(answer);
}
然后使用事件處理程式代替 v-model:
<QuestionItem
v-for="(question, index) in questions"
:key="index"
:question="question"
:index="questionIndex"
@input="answerChanged" //bind the event handler
class="flex-none w-full"
/>
最后,您需要將 questionId 添加到您發出的值中。這是一個近似值,您可能需要對其進行調整以適合您正在尋找的確切格式:
watch: {
questionValue(newValue) {
// emit the value that we want for a single answer in our parent answers array
this.$emit('input', {
questionId: question.id,
questionOptionIds:question.options,
answer: newValue
})
},
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397314.html
標籤:javascript 数组 Vue.js 目的 发射
上一篇:JavaScript通過一個或兩個鍵對物件陣列進行分組和轉換
下一篇:如何回圈回陣列中的第一項?
