【问题标题】:Create an aswers array from a child component then emit this array to the parent in Vue.js 2从子组件创建一个 aswers 数组,然后将此数组发送到 Vue.js 2 中的父组件
【发布时间】:2021-12-29 15:15:21
【问题描述】:

我正在使用 Vue 2 构建调查,我正在尝试构建答案数组并将其发送到名为 Evaluation 的父组件,如下所示:https://pastebin.com/rLEUh56a

我有一个名为 QuestionItem.vue 的组件,它是 Evaluation 的子组件,如下所示:https://pastebin.com/RFPgKs5Q

answers 数组必须是这样的才能发送到 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.typetextrangestarsfaces,则questionOptionIds 需要为空并且answer 属性需要是应答值,但如果@ 987654331@ 是radiocheck,answer 属性必须为空,questionOptionIds 属性需要是用户选择的 answer 选项。

我不确定如何从 QuestionItem.vue 组件中输入的每个答案构建这个数组。

感谢您的宝贵时间,祝您有美好的一天!

【问题讨论】:

    标签: javascript arrays vue.js object emit


    【解决方案1】:

    您不能像这样在 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 将获取您从孩子发出的输入值并将其设置为答案,在这种情况下这没有任何意义,因为答案是每个答案的数组,而不是单个答案。

    您将需要在您的父组件中拥有一个自定义事件处理程序。像这样的:

    // 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
            })
        },
    },
    

    【讨论】:

    • 非常感谢,它似乎有效,现在我需要构建答案对象并根据question.type放置值
    • 这可能发生在您的 questionValue 的问题组件观察器中
    • 是的,想通了,非常感谢!
    猜你喜欢
    • 2020-11-20
    • 2018-07-07
    • 2019-04-11
    • 2019-03-04
    • 2017-09-13
    • 2021-12-24
    • 2020-09-28
    • 2017-06-10
    • 2016-11-14
    相关资源
    最近更新 更多