Categories
Vue 3 Projects

Create a Digital Clock App with Vue 3 and JavaScript

Spread the love

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 digital clock 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 digital-clock

and select all the default options to create the project.

Create the Digital Clock App

We can create a digital clock app with the following code:

<template>
  <div>{{ dateTime.hours }}:{{ dateTime.minutes }}:{{ dateTime.seconds }}</div>
</template>

<script>
const date = new Date();
export default {
  name: "App",
  data() {
    return {
      dateTime: {
        hours: date.getHours(),
        minutes: date.getMinutes(),
        seconds: date.getSeconds(),
      },
      timer: undefined,
    };
  },
  methods: {
    setDateTime() {
      const date = new Date();
      this.dateTime = {
        hours: date.getHours(),
        minutes: date.getMinutes(),
        seconds: date.getSeconds(),
      };
    },
  },
  beforeMount() {
    this.timer = setInterval(this.setDateTime, 1000);
  },
  beforeUnmount() {
    clearInterval(this.timer);
  },
};
</script>

In the template, we display the hours, minutes, and seconds with dateTime.hours , dateTime.minutes and dateTime.seconds respectively.

In the data method, we return the dateTime object with the hours , minutes , and seconds property.

new Date() returns an object the current date and time.

getHours returns the hour of the date.

getMinutes returns the minutes of the date.

getSeconds returns the seconds of the date.

In the setDateTime method, we get the current date with new Date() .

And we call getHours , getMinutes , and getSeconds to get the time parts.

In the beforeMount hook, we call setInterval with the this.setDateTime method to run it every second.

The 2nd argument specifies that it runs every 1000 milliseconds, which is 1 second.

It returns the timer object which we assign to the timer reactive property.

beforeMount runs when the component is mounting.

beforeUnmount calls the clearIntrval method with the timer reactive property to clear the timer when the component unmounts.

In the template, we show the time and it updates every second.

Conclusion

We can create a digital clock easily with Vue 3 and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *