Vue Data Binding Example

I started going through some Vue tutorials and put together a little Vue js page. It takes user input, validates it against a data object value. Depending on the result, a dynamic element is updated on the page.

Math Problem Generator

Below is a Math problem generator (multiplication). I created this for my son to learn his times tables. The first question is hard coded (8 * 7), but after that, it calls a method to generate a random multiplication problem. The answer is calculated and the user input is compared against the calculated result.

A score is tallied (of correct and incorrect answers). Afterwards, a percentage is calculated at the end of each question. The code listens for both the button click, or hitting the ENTER key. The Enter key is the easiest to use. Input a value in the field, hit enter, repeat.

Solve: {{ title }}

Input Answer:

{{ result }}

Percentage Right: {{percentCorrect}}

The code

The code for the above little exercise is below. I put everything in one HTML file, for convenience:

<div id="math" class="mx-auto" style="width: 400px; background-color: lightblue;"> Solve: <strong>{{ title }}</strong> <p> Input Answer: <input v-model="userAnswer" type="text" @keyup.enter="checkAnswer(userAnswer)"> <button class="btn btn-primary" @click="checkAnswer(userAnswer)">Submit</button> <div> {{ result }} <p></p> </div> <div> Percentage Right: <strong>{{percentCorrect}}</strong> </div> </div> <script src="https://unpkg.com/vue"></script> <script> let correctAnswer = 0 let wrongAnswer = 0 let mathQuestion = new Vue({ el: '#math', data: { title: '8 x 7', answer: 8*7, result: '', percentCorrect: `0%` }, methods: { checkAnswer: function() { Number(this.userAnswer) === Number(this.answer) ? this.updateScore(true) : this.updateScore(false) this.createMathProblem() }, createMathProblem: function() { this.userAnswer = '' firstNumber = Math.floor(Math.random() * 10) secondNumber = Math.floor(Math.random() * 10) this.title = `${firstNumber} * ${secondNumber}` this.answer = firstNumber * secondNumber }, updateScore: function(isCorrect) { if(isCorrect){ this.result = "Correct Answer" correctAnswer += 1 }else{ this.result = `Wrong Answer, ${firstNumber} * ${secondNumber} = ${firstNumber * secondNumber}` wrongAnswer += 1 } this.percentCorrect = `${Number(correctAnswer)} / ${wrongAnswer + correctAnswer} = ${Number(correctAnswer/(correctAnswer+wrongAnswer)).toPrecision(4) * 100}%` this.createMathProblem() } } }) </script>

Leave a Reply

Your email address will not be published. Required fields are marked *