Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get update the current timestamp without refreshing the page in vue.js?

In my vue application i am using a method to get current timestamp , i am getting the current time and date but its get updated only after refreshing the page , i want it get updated dynamically without page refresh.

i guess I need to include something like set interval not sure how to implement

<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>
like image 984
NandhaGopalElangovan Avatar asked Sep 12 '25 20:09

NandhaGopalElangovan


1 Answers

Add range time of 1s in created hook like :

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

Full 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>
like image 141
Boussadjra Brahim Avatar answered Sep 14 '25 11:09

Boussadjra Brahim