Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a guess a number game with Vue 3 and JavaScript.
Create the Project
We can create the Vue project with Vue CLI.
To install it, we run:
npm install -g @vue/cli
with NPM or:
yarn global add @vue/cli
with Yarn.
Then we run:
vue create number-guessing-game
and select all the default options to create the project.
Create the Guess a Number Game
To create the guess a number game, we write:
<template>
<div v-if="started">
<form @submit.prevent="submit">
<div>
<label>answer</label>
<input v-model.number="answer" />
</div>
<button type="submit">check</button>
</form>
<p>{{ status }}</p>
</div>
<div v-else>
<button type="button" @click="start">start</button>
<p>{{ status }}</p>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
rightAnswer: undefined,
answer: 0,
status: "",
started: false,
};
},
computed: {
formValid() {
return +this.answer >= 0;
},
},
methods: {
start() {
this.rightAnswer = Math.ceil(Math.random() * 10);
console.log(this.rightAnswer);
this.started = true;
},
submit() {
if (!this.formValid) {
return;
}
const { answer, rightAnswer } = this;
if (answer === rightAnswer) {
this.status = "you got it";
this.started = false;
} else if (answer < rightAnswer) {
this.status = "too low";
} else {
this.status = "too high";
}
},
},
};
</script>
We start by adding the form div that’s shown when the game is started.
It’s started when started
is true
.
Inside it, we have a form element.
We listen to the submit
evbent with the @sumbit
directive.
The prevent
modifier prevents server-side submission and let us do client-side form submission.
We have an input to let the player enter the answer.
We bind the inputted value to the answer
reactive property with v-model
.
The number
modifier automatically converts the entered value to a number.
Then we add a button with type
set to submit
to let the player submit the form.
We also display the status
in the form.
If the game isn’t started, we display the status
and a button to let us start the game.
Then we move on to adding the component options object.
Inside it, we have the data
method to return the reactive properties and their initial values.
Next, we add the formValid
to check the answer
reactive property to see if it’s bigger than or equal to 0.
The start
method lets us start the game by generating the rightAnswer
and set started
to true
to start the game.
Next, we add the submit
method to compareanswer
with the rightAnswer
.
First, we check if the value is a valid number with formValid
.
If it’s not, then we stop running the function.
And we display different messages depending on whether answer
is equal, less than, or bigger than the rightAnswer
.
If the player got the right answer, then we set started
to false
to end the game.
Conclusion
We can create a guess the number game easily with Vue 3 and JavaScript.