A
A
Alexey Sklyarov2019-04-22 12:07:07
Vue.js
Alexey Sklyarov, 2019-04-22 12:07:07

Why is v-model not connected by object value?

I am writing a simple test, questions are taken from a JSON file, the answers for which can be selected either through a radio button or through a checkbox. In order to send all the answers to the test, I created an array result, in each element of which I placed an object with the title of the question and the answer to this question.

Open Code
import questions from './json/seven_layers_of_fog.json';
export default {
  components: { DatePicker,TheMask },
  data: function() {
    return {
      title: questions.title,
      questions: questions.questions,
      result: []
    }
  },
  created(){
    for (var i = 0; i < this.questions.length; i++) {
      this.result[i] = {
        'title' : this.questions[i].text,
        'answer' : ''
      }
    }
  },
}


The resulting array looks like this:
Open Image
5cbd831e6d91a451153874.png

Next, I mark up the questions:
Open Code
<template>
  <div class="quiz">
    <h1>{{title}}</h1>
    <div v-for="(question,index) in questions" class="quiz__question question" v-if="result.length > 0">
        <div class="question__title">
          {{index+1}}. {{question.text}}:
          <div v-if="question.required" class="question__required">*</div>
        </div>
        <div class="question__answers">
          <div v-for="(ans,i) in question.answers" class="question__answer">
            <input :type="question.type" v-model="result[index].answer" :value="ans" :id="'q'+index+'a'+i">
            <label :for="'q'+index+'a'+i">{{ans}}</label>
          </div>
        </div>
    </div>
    <button class="button" name="button">Закончить тест</button>
  </div>
</template>


And here in the line:
<input :type="question.type" v-model="result[index].answer" :value="ans" :id="'q'+index+'a'+i">
v-model doesn't work for me. If I attach to the field of the object of any element of the array, then when selecting checkboxes or radio buttons, there is no interaction. If I mount like this:
<input :type="question.type" v-model="result[index]" :value="ans" :id="'q'+index+'a'+i">
, then everything works, but as you understand, the object from the array element is erased.
Is it possible how to fix this problem?
PS Perhaps there are easier ways to save the values ​​of the selected checkboxes (as values, not true/false), given that instead of checkboxes there can be radio buttons that properly return the value of the input.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alex, 2019-04-22
@0example

try result[index].answerto make it an array

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question