[Vuejs]-Vue – Push for nested object

0πŸ‘

βœ…

I’ve been able to get this to work. My modified working code is below for anyone interested. Note that I have added 2 extra buttons to allow the removal of questions and answers.

<div v-for="(form, fIndex) in forms" :key="form.id">
          <q-field class="q-mb-sm" label="Form Title: " helper="Please enter the title of the form.">
            <q-input v-model="form.name" type="text" clearable />
          </q-field>
          <q-card-separator class="q-mb-md q-mt-xl"/>
       <div v-for="(question, qIndex) in form.questions" :key="question.id">
        <q-btn class="q-mb-md" round size="sm" color="amber" icon="add" @click="addRowQuestions(fIndex)" />
        <q-btn class="vertical-top" v-show="qIndex !==0" round size="sm" color="blue" icon="remove" @click="remRowQs(fIndex)" />
        <q-field class="q-mb-sm" label="Question Title: " >
          <q-input v-model="question.text" />
        </q-field>
        <q-card-separator class="q-mb-md q-mt-xl"/>
          <div v-for="(answerChoice, aIndex) in question.answerChoices" :key="answerChoice.id">
            <q-btn class="q-mb-md" round size="sm" color="green" icon="add" @click="addAnswers(fIndex, qIndex)" />
            <q-btn class="vertical-top" v-show="aIndex !==0" round size="sm" color="negative" icon="remove" @click="remRowAns(fIndex, qIndex)" />
            <q-field class="q-mb-sm" label="Answer ID: ">
              <q-input v-model="answerChoice.answerId" type="number" clearable />
            </q-field>
        <q-card-separator class="q-mb-md q-mt-xl"/>
          </div>
       </div>
       </div>

    methods: {
    addRowQuestions (fIndex) {
      this.forms[fIndex].questions.push({
        qtext: '',
        answerChoices: [
          {
            answerId: ''
          }
        ]
      })
    },
    addAnswers (fIndex, qIndex) {
      this.forms[fIndex].questions[qIndex].answerChoices.push({
        answerId: ''
      })
    },
    remRowQs (fIndex) {
      this.forms[fIndex].questions.splice(fIndex, 1)
    },
    remRowAns (fIndex, qIndex) {
      this.forms[fIndex].questions[qIndex].answerChoices.splice(qIndex, 1)
    }
  }
}

0πŸ‘

You’re not creating a new form, just a new question in forms[0] when you are adding a question. So there is no β€˜this.forms[1]’ and thus this.forms[1].questions is undefined.

Leave a comment