What is the best way to update the current timestamp dynamically in Vue.js without needing to refresh the page?

I have a Vue application where I am using a method to retrieve the current timestamp. Although it successfully displays the current time and date, it only updates upon page refresh. I would like for it to update dynamically without requiring a page refresh.

I assume that I need to incorporate something like setInterval, but I am unsure of how to implement it.

<html>
   <head>
      <title>VueJs Introduction</title>
      <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js">
      </script>
   </head>
   <body>
      <div id = "intro" style = "text-align:center;">
         <h1>{{ timestamp }}</h1>
      </div>
      <script type = "text/javascript">
         var vue_det = new Vue({
            el: '#intro',
            data: {
               timestamp: ''
            },
            created() {
                this.getNow();
            },
            methods: {
                getNow: function() {
                    const today = new Date();
                    const date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
                    const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
                    const dateTime = date +' '+ time;
                    this.timestamp = dateTime;
                }
            }
         });
      </script>
   </body>
</html>

Answer №1

To incorporate a range time of 1 second in the created hook, you can add the following code:

setInterval(() => {
  this.getNow();
}, 1000)

Here is a complete example:

var vue_det = new Vue({
  el: '#intro',
  data: {
    timestamp: ''
  },
  created() {
    setInterval(() => {
      this.getNow();
    }, 1000)
  },
  methods: {
    getNow: function() {
      const today = new Date();
      const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
      const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
      const dateTime = date + ' ' + time;
      this.timestamp = dateTime;
    }
  }
});
<html>

<head>
  <title>VueJs Introduction</title>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js">
  </script>
</head>

<body>
  <div id="intro" style="text-align:center;">
    <h1>{{ timestamp }}</h1>
  </div>
  <script type="text/javascript">
  </script>
</body>

</html>

Answer №2

Calling this.getNow() only once is recommended. Using setInterval is another option, where you can set it for 1000ms like this:

let vue_det = new Vue({
  el: '#intro',
  data: {
    timestamp: ''
  },
  mounted: function () {
    setInterval(function () {
      this.getNow()
    }.bind(this), 1000)
  }
});

Alternatively, in ES6 syntax:

setInterval(() => { this.getNow() }, 1000)

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

Encountering an unexpected end of input error while making an API call using the fetch()

I'm looking to transition an API call from PHP to Javascript for learning purposes. Unfortunately, I can't make any changes on the API side as it's an external source. When attempting to use fetch() due to cross-origin restrictions, my scrip ...

Extracting a single string from a JSON object: A step-by-step guide

Currently, I am working on retrieving a JSON document from my MongoDB. Once fetched, my goal is to extract only the "email" field so that I can utilize it for sending emails to users. setInterval(()=>{ return User.find({email: &apos ...

Sorted Array Resulting from Execution of For Loop

My goal is to calculate the distance between two sets of latitude and longitude coordinates using the npm geolib library. I have a function that queries Firestore and retrieves an array of objects. Within this array, I iterate through each object in a for ...

The form validation feature suddenly stopped functioning after implementing ajax submission on the page

I originally had a conventional form submission page with form validation JavaScript that was functioning properly. After switching the page to submit via AJAX, the form validation is no longer being triggered. How can I integrate the two methods to ensu ...

What is the best way to eliminate the "1 empty item" from a JSON object using JavaScript?

This is an example json object that has been modified to remove certain values. { name: { first: 'Robert', middle: '', last: 'Smith' }, age: 25, DOB: '-', hobbies: [ 'running', 'coding', & ...

Retrieving information from an object using JavaScript

Hello, I am facing a challenge with extracting data from an object via a web API in ReactJS. It seems like the data returned by the API is not structured properly as a JavaScript object. To view the issue directly in your browser visit: I need assistance ...

Enabling the use of jQuery with Angular instead of JQLite

According to the angular DOCS, if jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to AngularJS's built-in subset of jQuery, known as "jQuery lite" or jqLite. In an attemp ...

The HTML function transforms blank spaces into the symbol "+"

Just starting out with a question: I created a basic submission form, but I noticed that if there are any spaces in the inputs, the values get changed to a plus sign (+). Here's my form: <form name="input" action="search" method="get"> Web Ad ...

Limiting page entry with passport.js and express middleware

My server is set up to authenticate user login. I have successfully redirected users to the success page after authentication (and back to the login page if it fails). However, I am facing an issue with using my own express middleware to restrict access fo ...

The API has been triggered twice

I am currently working on a React component where I have implemented an API call using the useEffect hook with an empty dependency array. However, I noticed that the API is being called twice and I can't seem to find the reason behind it. import { use ...

Leverage the generic types of an extended interface to simplify the creation of a shorthand type

Attempting to streamline my action shorthand that interacts with AsyncActionCreators. A function has been crafted to accept a React dispatch: Dispatch<T> parameter: const fetchProfileAction = actionCreator.async<void, Profile, any>('FETC ...

sending data to Google Maps and updating it

OPERATING SMOOTHLY My requirement is to display only the items that match the entered username and password. I am unable to pass PHP variables to JavaScript in order to query the database and update the map. The following code is functioning correctly (p ...

Rebalancing Rotation with Three.js

Currently, I am utilizing Three.js and my goal is to swap out an object in the scene with a new one while maintaining the same rotation as the one I removed. To achieve this, I take note of the rotation of the object I'm removing and then utilize the ...

Tips for customizing the appearance of the day button in a React Material-UI date picker

In my React project, I am using material-ui date picker and I am looking for a way to customize the styling of the day buttons. Specifically, I want to change the text color of the available days. By default, as seen in the screenshot, the text color is bl ...

When I make changes to the current user, it appears that all collections are being cleared, though this is

While developing a website using angular-meteor, I encountered an unusual issue. Each page on my site features a chat block where messages are stored in the chatMessages collection and displayed correctly. However, whenever I modify the current user (eithe ...

Navigating with Three.JS FPS controls by moving left and right

Currently, I am working on a demo to check player controls for a FPS game. The camera rotation is controlled by the mouse, and the player can move using W-A-S-D keys. However, I am facing an issue with implementing movement left and right relative to the d ...

Passing props to another component using the <Link> element in React Router

I'm working on a project where I need to display search results using an array. When a user clicks on an item, I want to pass that item as props rather than as parameters. Below is the code snippet: { this.props.results.map((result) => { ...

Using Typescript to import functions

TLDR - I need help understanding the difference between these imports in ReactJs using Typescript: setState1: (numbers: number[]) => void, setState2: Function Hello everyone, I've encountered some strange behavior when importing functions with Typ ...

Having Trouble Loading PHP File with Jquery

I've been struggling with using JQuery/Ajax to load the content of my PHP file into a div tag. Below is the code snippet from my page that attempts to load the file: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/ ...

Vue Router encountered a TypeError when attempting to call "set name" on an object that does not adhere to the HTMLFormElement interface

I'm encountering a strange issue with vue-router that I can't seem to debug. Below is my routes.ts file: import Navbar from '@/layout/Navbar.vue' import SidebarMenu from '@/layout/SidebarMenu.vue' import Footer from '@/ ...