【问题标题】:How to put just a value from a radio input into an array in Vuejs and Vuex如何将无线电输入中的一个值放入 Vuejs 和 Vuex 中的数组中
【发布时间】:2020-02-10 05:01:13
【问题描述】:

state: {
		questions: [
		{
			"id": 1,
			"name": "q1",
			"category": "English Language",
			"type": "multiple",
			"question": "What is a name of any person, animal, place, thing and feeling?",
			"correct_answer": "Noun",
			"incorrect_answers": [
			"Pronoun",
			"Noun",
			"Adverb",
			"Adjective"
			]
		}
    ]
    answer = "",
    answer = []
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

我正在开发一个测验应用程序,并且正在使用 Vuex 进行状态管理。我对每个问题都有四个单选值(答案),我只想将最后一个选择的值(答案)放入一个处于我的 Vuex 状态的数组中,它工作正常,但每当用户选择另一个单选输入(来自同样的问题)它也进入了数组,而我只想要每个问题中的选定值(无论选项中的切换数量如何)。

我的状态为 10(长度)的“问题”数组如下所示:

state: {
        questions: [
            {
            "id": 1,
            "name": "q1",
            "category": "English Language",
            "type": "multiple",
            "question": "What is a name of  person, animal, place or thing?",
            "correct_answer": "Noun",
            "incorrect_answers": [
            "Pronoun",
            "Noun",
            "Adverb",
            "Adjective"
            ]
}
...
   }

我的模板如下所示:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
```
<div class="card-text ml-4" v-for="(answer, index) in question.incorrect_answers" :key="index" >
  <label class="form-check-label">
    <!-- <input type="radio" name="answer" class="mb-2" v-model="getAnswers[index]" :value="answer"> {{answer}} -->
    <input type="radio" :name="question.name" class="mb-2" :value="answer" @change.stop="newAnswer(question.id, answer)" /> {{answer}}
  </label> <!-- work on postanswer -->
</div>
```

我的变异看起来像这样:

mutations:{
		ANSWER(state, id, ans){
			state.answer = id;
			if(id === "q1"){
				state.answers.push(state.answer);
			} else {

			}
		}
 }
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"&gt;&lt;/script&gt;

我已经用了好几个星期了,但我没有得到它。我该怎么做?

【问题讨论】:

    标签: vuejs2 radio-button vuex vue-cli-3


    【解决方案1】:

    将答案放入数组的逻辑

    1. 使用数组索引检查答案是否已经输入
    2. 如果存在删除旧的并插入最新的选择

    这里是上述逻辑的代码

      // Trying to find index of chosed answer
      const indexOfExistingChoice = this.choosedAnswers.findIndex(
        answer => answer.id === selectedAnswer.id
      );
    
      if (indexOfExistingChoice >= 0) {
        // Choice already selected
        // Removing the choice from the array
        this.choosedAnswers.splice(indexOfExistingChoice, 1);        
      }
    
      // Pushing into the array
      this.choosedAnswers.push(selectedAnswer);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      • 2019-01-11
      • 2020-11-03
      • 2016-04-21
      • 1970-01-01
      相关资源
      最近更新 更多