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 dice 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 dice-game
and select all the default options to create the project.
Create the Dice Game
To create the dice game, we write:
<template>
<div>
<button @click="roll">roll</button>
<p>rolled dice value: {{ rolledValue }}</p>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
rolledValue: 1,
};
},
methods: {
roll() {
this.rolledValue = Math.ceil(Math.random() * 5 + 1);
},
},
};
</script>
We have the roll button that calls roll
when we click on it.
The rolledValue
is displayed below it.
In the script tag, we have the data
method that returns an object with the rolledValue
reactive property.
The roll
method sets the rolledValue
to a random number between 1 and 6.
Math.random
returns a number between 0 and 1, so we’ve to multiply the returned value by 5 and add 1 to get a value between 1 and 6.
Math.ceil
returns a number rounded up to the nearest integer.
Conclusion
We can create a dice game easily with Vue 3 and JavaScript.