Home > Web Front-end > Front-end Q&A > How to implement Vue fill-in-the-blank questions

How to implement Vue fill-in-the-blank questions

WBOY
Release: 2023-05-18 10:06:08
Original
1218 people have browsed it

Vue's implementation of fill-in-the-blank questions can be done by using the v-for and v-model instructions, as well as arrays to process the data in the blanks.

A simple implementation is to create an array containing all the answers in the blanks, then traverse the array through the v-for directive, and use the v-model directive to two-way bind the answers in each blank. As the user fills in their answers, the corresponding array elements are updated.

The following is an example showing how to use Vue to implement fill-in-the-blank questions:

HTML template:

<div id="app">
  <h2>请完成以下句子:</h2>
  <p>1. 我们___喝珍珠奶茶,你___喝咖啡。</p>
  <p>
    <span v-for="(ans, index) in answers" :key="index">
       <input type="text" v-model="ans">
       <span v-if="index === answers.length - 1">.</span>
       <span v-else>,</span>
    </span>
  </p>
  <button @click="checkAnswers">提交</button>
</div>
Copy after login

Vue instance:

var vm = new Vue({
  el: '#app',
  data: {
    answers: ['', ''],
    correctAnswers: ['我们', '你']
  },
  methods: {
    checkAnswers: function() {
      for (var i = 0; i < this.answers.length; i++) {
        if (this.answers[i] !== this.correctAnswers[i]) {
          alert('回答错误!');
          return;
        }
      }
      alert('回答正确!');
    }
  }
})
Copy after login

In the above example, We created a fill-in-the-blank question with two blank spaces. Each blank has an array element to store the answers filled in by the user. We also create an array of correct answers to use when checking answers.

Use the v-for instruction to traverse the answers array, create corresponding input boxes and punctuation marks, and use the v-model instruction to bind each input box to its corresponding array element. The submit button calls the checkAnswers method to check all answers. If an error is detected, a pop-up window will prompt the user to answer the question incorrectly.

In general, by using Vue’s v-for and v-model directives, we can easily implement fill-in-the-blank questions. This method is concise, clear, easy to maintain, and suitable for various forms of fill-in-the-blank questions.

The above is the detailed content of How to implement Vue fill-in-the-blank questions. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template