TOC
wwworkshop
Juicy Workshop

3.7.4.1
Clock

This example application is simply displaying the current time.

The Vue.js app has a single data property time. The property is updated every second with the current time.

???

The created function can be used to execute some code when the Vue.js app is created. In this case, it contains a call to setInterval, which is a JavaScript function to set up some code to be executed regularly in set intervals. The interval is given in milliseconds (1000ms = 1s).

The time is obtained from the current Date by using getHours, getMinutes and getSeconds.

index.html

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clock</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="app">
        <p>{{ time }}</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 {
            time: '-:--:--'
        }
    },

    created () {
        setInterval(() => {
            let date = new Date()
            this.time = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
        }, 1000)
    }
}).mount('#app')

style.css

p {
    font-family: sans-serif;
    font-size: 30px;
    text-align: center;
    margin-top: 50px;
}