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 coin flip app 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 coin-flip
and select all the default options to create the project.
Create a Coin Flip App
To create the coin flip app, we write:
<template>
<div>
<h1>select a face</h1>
<button @click="selectedFace = 'heads'">heads</button>
<button @click="selectedFace = 'tails'">tails</button>
</div>
<p>you selected: {{ selectedFace }}</p>
<p>computer selected: {{ computerSelectedFace }}</p>
<button @click="flip">flip coin</button>
<p v-if="isWin">you win</p>
<p v-else>you lost</p>
</template>
<script>
const faces = ["heads", "tails"];
export default {
name: "App",
data() {
return {
selectedFace: "",
coinFlipResult: "",
};
},
computed: {
computerSelectedFace() {
const { selectedFace } = this;
const face = faces.find((f) => f !== selectedFace);
return face;
},
isWin() {
const { selectedFace, coinFlipResult } = this;
return coinFlipResult === selectedFace;
},
},
methods: {
flip() {
let index;
if (Math.random() < 0.5) {
index = 0;
} else {
index = 1;
}
this.coinFlipResult = faces[index];
},
},
};
</script>
In the template, we have a heads button to let the player select heads.
And we have another button to lets the player select tails.
Once a button is clicked, the selectedFace
value is set.
Then we have the p elements to show the selected coin face of the player and the computer.
Next, we add a flip coin button to let us flip the coin.
Then we display if the player won or lost in the p elements.
Next, in the script
tag, we have the faces
array with the 'heads'
and 'tails'
strings.
data
returns an object with the reactive properties and their initial values.
Next, we have the computed properties.
We have the computedSelectedFace
which returns the coin face that the computer chooses, which is the one the player didn’t choose.
isWin
checks if coinFlipResult
is the same as seletedFace
, which indicates that the player wins.
And finally, we have the flip
method to set coinFlipResult
to set the coin flip result.
Conclusion
We can create a coin flip app easily with Vue 3 and JavaScript.