TOC
wwworkshop
Juicy Workshop

3.7.4.2
Dice

This example application simulates a dice. It contains a button with an event listener for the click event. Event listeners in Vue.js can be attached to elements using the @-prefix. In this case the rollDice method is called when the user clicks the button.

???

The rollDice method is generating a random number (Math.random()), scales it to the range from 0 up to 6 exclusively (* 6), converts it to a whole number (Math.floor()) and adds one, so the result is in the range from 1 to 6 inclusively.

The number is assigned to the result property which is in turn displayed on the page.

index.html

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dice</title>
</head>
<body>
    <div id="app">
        <button @click="rollDice">roll dice</button>
        <p>{{ result }}</p>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="script.js"></script>
</body>
</html>

script.js

const { createApp, ref } = Vue

createApp({
    data () {
        return {
            result: ''
        }
    },

    methods: {
        rollDice () {
            this.result = Math.floor(Math.random() * 6) + 1	
        }
    }
}).mount('#app')

style.css

* {
    font-family: sans-serif;
    text-align: center;
}

button {
    font-size: 40px;
    background: green;
}

p {
    font-size: 120px;
}