刷新 v-model

Refresh v-model

我正在开发试卷应用程序。

一旦我输入问题并点击“+”按钮,问题就会进入试卷数组,计数器加一。 问题是在我点击“+”按钮后,我之前输入的问题仍然在 UI 的字段中。 因为我使用v-model绑定数据字段

我想要的是一种清除UI中那些以前问题数据的方法。 这类似于重置按钮功能。

<template>
  <div>
    <div class="container" v-if="counter<=5">
      <h2>Question {{counter}}</h2><hr>

      <textarea rows="7" cols="75" v-model="question"></textarea><br><br>

      1. Answer <input type="text" v-model="answer1"> <input type="radio" name="q1answer" value="1" v-model="correctAnswer"><br><br>
      2. Answer <input type="text" v-model="answer2"> <input type="radio" name="q1answer" value="2" v-model="correctAnswer"><br><br>
      3. Answer <input type="text" v-model="answer3"> <input type="radio" name="q1answer" value="3" v-model="correctAnswer"><br><br>
      4. Answer <input type="text" v-model="answer4"> <input type="radio" name="q1answer" value="4" v-model="correctAnswer"><br>
      <hr>

      Knowledge Area <select v-model="knowledgeArea">
        <option value="Maths">Mathematics</option>
        <option value="Language">Language Skills</option>
        <option value="gk">General Knowledge</option>
          <option value="other">Other</option>
      </select><br><br>
      <button type="button" class="btn" @click="pushToArray" >
      <span class="glyphicon glyphicon-plus"></span></button>
    </div>
    <div v-if="counter>5">
      <button type="button" class="btn btn-primary" @click="onSubmit">Save Question Paper</button>
    </div>
</div>
</template>
<script>
import axios from 'axios';
var questionPaper = [];
export default {

    data () {

      return {
        question:'',
        answer1:'',
        answer2:'',
        answer3:'',
        answer4:'',
        correctAnswer:'',
        knowledgeArea:'',
        counter:1,
        show:true

      }
    },
    methods: {

      onSubmit () {

      },

      pushToArray(){
        const formData = {
          question: this.question,
          correctAnswer: this.correctAnswer,
          answer1: this.answer1,
          answer2: this.answer2,
          answer3: this.answer3,
          answer4: this.answer4,
          knowledgeArea:this.knowledgeArea

        }
        this.counter++;
        questionPaper.push(formData);

      }
    }
  }

</script>

创建一个模板 数据变量用作重置。例如

const templateData = {
  question:'',
  answer1:'',
  answer2:'',
  answer3:'',
  answer4:'',
  correctAnswer:'',
  knowledgeArea:''
}

export default { // ...

用它来设置你的初始数据

data() {
  return {
    counter: 1,
    show: true,
    ...templateData
  }
}

现在您可以在 pushToArray 方法中轻松重置您的数据,例如

questionPaper.push(formData);
Object.assign(this, templateData);