Automatically Refreshing on Vue.js: Embracing the Passage of Time

I want to display this clock on Vue. The clock should automatically update the time, but how can I make this code work in Vue?

Is there a simple way to implement this in Vue without using (document.getElementBy...)

function updateTime () {
    document.getElementById("time").innerHTML = new Date().toLocaleTimeString();
}
var timeInterval = setInterval(updateTime, 1000);

<div id="time"></div>

Answer №1

Check out this Vue 3 code snippet:

<template>
   <h1>Greetings World! {{ currentTime }}</h1>
</template>

<script>
import { ref } from 'vue'

export default {
  setup () {
    var currentTime = ref()
    setInterval(() => {
      currentTime.value = new Date().toLocaleTimeString()
    }, 1000)

    return { currentTime }
  }
}
</script>

Answer №2

Instead of relying solely on document.getElementById, you have the option to utilize refs in the following manner:

new Vue({
  el:"#app",
  mounted() {
    var timeInterval = setInterval(this.time, 1000);
  },
  methods: {
    time: function() {
      this.$refs.time.innerHTML = new Date().toString("hh:mm:ss tt");
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div ref="time"></div>
</div>

Alternatively, you can achieve the same result by updating a data attribute like so:

new Vue({
  el:"#app",
  data() { return { time: "" } },
  mounted() { 
    var timeInterval = setInterval(this.updateTime, 1000);
  },
  methods: {
    updateTime: function() {
      this.time = new Date().toString("hh:mm:ss tt");
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div>{{time}}</div>
</div>

Answer №3

In Vue Js, you have the ability to create a digital clock that dynamically updates its time value in real-time by utilizing the setInterval() method. Take a look at the code snippet below for an example:

const {ref, createApp} = Vue

createApp({
    setup() {
        //declare date variable using reactivity API
        const date = ref(new Date())
        //periodically update date value with setInterval() method
        setInterval(() => {
            date.value = new Date()
        }, 1000)

        return {
            date
        }
    }
}).mount('#app')
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e181b0b2e5d405f405f">[email protected]</a>/dist/vue.global.prod.js"></script>

<div id="app">
      <h3> {{date.getHours()}}:{{date.getMinutes()}}:{{date.getSeconds()}}</h3>
</div>

When viewed in the browser, the output will display something like this: 21:31:05

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the values of a function using the Firebase database

Hey, I'm in a bit of a pickle trying to retrieve the values returned by my function. I can see them just fine in the console log, but how do I actually access them when calling the function? function getprofile(useruid) { return firebase.database ...

Comparing two tables in jQuery/Javascript for matching data

I want to check for matches between the rows of two HTML tables, where the data in the first cell can be duplicated but the data in the second cell is always unique. The goal is to determine if the combination of values in the first and second cells of tab ...

Tips for maintaining the data on a page continuously updating in AngularJS

I have this code snippet: $cookieStore.put('profileData', $scope.profileData); var profileData = $cookieStore.get('profileData'); $scope.init = function(){ var profileData = $cookieStore.get('pr ...

Is the Angular $watch function able to track changes on an object's prototype members as well?

I have encountered a challenge with a tree structure implemented in Javascript which has circular references. The objects in the structure contain an array of children, but these children also need to reference their parent for deletion purposes. To monit ...

Troubles with Angular elements not aligning correctly when using the "display: block" property

When using an angular element for a directive with "display: block", it may not automatically take up 100% of the width of the parent container. In order to ensure that it does, the width must be explicitly set to "100%" in the CSS. Despite setting "width: ...

The function inArray() in jQuery will return a value of -1 when an array consists of

When using jQuery inArray, if the array contains only one element, it will return -1. var a = Array(1); console.log($.inArray(1,a)); This result is -1. However, if the array has 2 or more elements, it functions correctly. var a = Array(1,2,3); console.l ...

Challenges arise when adjusting frame size for mobile and desktop devices

I am trying to achieve an auto-resize feature for my frame's height when the screen width is smaller than a certain value. I want it to behave like Sketchfab, as demonstrated in this video: http://www.youtube.com/watch?v=_y5ckVFGHKU&feature=youtu. ...

Retrieving cached data using $http in AngularJS

When making a request to an API using $http in AngularJS, I am receiving cached results. Below is the AngularJS code snippet: $scope.validate = function(){ var encodedUserNameAndPassword = Base64.encode($scope.username + ':' + $scope.passwo ...

When invoked, a Javascript Object comes back empty

My code snippet: const channels = fauna.paginate(q.Match(q.Index("channels"), "true")) // Query FaunaDB database for channel list => create constant called users containing results const channelList = channels.each(function (page) { ...

Application of id missing on all buttons in Bootstrap tour template

I'm having an issue with applying a new id to the next button in a Bootstrap tour template. I added the id to the button, but it only seems to work for the first stage and not the subsequent ones. Can anyone provide insight into why this might be happ ...

A method for extracting URL parameters based on the matching route path

Is it possible to parse a given URL string in relation to the match.path value? For instance, if the current route is: <Route path="/some/path/:type" /> To obtain the type parameter of the current URL, one can simply use match.params.type ...

Regular expression pattern for consistently capitalizing the phrases "CA" and "USA" in an address string

end_address = 'joe's home, 123 test avenue, los angeles, ca, usa 90210'; end_address = end_address.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); The outcome of this code will ...

The functionalities of Google Maps are experiencing issues within AngularJS when utilizing the $route feature

Having Issues with Google Maps in AngularJS when using <ng-view></ng-view> Routing Configuration app.config(function($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); $routeProvider .when('/', { t ...

The TypeScriptLab.ts file is generating an error message at line 23, character 28, where it is expecting a comma

I am attempting to convert a ts file to a js file. My goal is to enter some numbers into a textarea, and then calculate the average of those numbers. However, I encountered an error: TypeScriptLab.ts(23,28): error TS1005: ',' expected. I have in ...

Using ternary operators and filters in a binding with AngularJS

I currently have a basic data binding setup: {{ myAccount.Balance }} Then I decided to incorporate a couple of filters: {{ myAccount.Balance | filter1 | filter2 }} Nevertheless, I am interested in using a ternary operator for scenarios where the Balanc ...

Can a custom spellchecking feature be integrated into an HTML textarea?

Question: I am wondering if it is feasible to incorporate a personalized spell checking feature into a Textarea field. Background: Currently, I am utilizing the b-form-textarea component from bootstrap-vue to present a textarea where users can input a li ...

Executing an xajax/ javascript function simultaneously

Is there a way to simultaneously execute the same function? Here is an example: function convert_points() { show_loading(); xajax_ConvertPoints(); xajax_GetRegularGamingCards(); } When xajax_ConvertPoints is called, there seems to be a mill ...

Refresh the information stored in the spliced array of objects

I've managed to splice the data and now I need to update its object from disabled = true to disabled = false. I have searched for another solution but couldn't find one... Any advice is welcomed. Thank you. This is my dropdown: const newDrop = ...

Secure Access with Skype Bot Verification

Recently, I managed to set up a NodeJS bot to synchronize messages between Discord and Skype chats. Although I am relatively new to Javascript and completely unfamiliar with NodeJS, the existence of a framework called Spype has been quite beneficial. The i ...

The (ReactJS + Redux) form fails to load when the /new segment is appended to the URL

I'm currently working on a project using React, Redux, and Rails. I've encountered an issue with loading the form. In my App.js file, I have set up a Router that defines the routes. import React, { Component } from 'react'; import { Br ...