Search code examples
javascriptvue.jsvuejs2momentjscomputed-properties

Get updated time information from momentjs in vuejs without refreshing the page?


I have a table where I display information about a site. One of these information is the last time data was refreshed.
On the top of the table, I would like to add an icon that appears only if the time between now and last time the data was refreshed is > 5 minutes. And I want this data to update without the user refreshing the page.

I added a this component in my vuejs code

computed () {
getMinutesPassedSinceLastRefresh () {
     if (moment(this.currentTime).diff(this.lastRefreshTime, 'minutes') >= 5) {
        return moment(this.currentTime).diff(this.lastRefreshTime, 'minutes')
      }
  }
}

This returns the number of minutes between last time data was refreshed and the current time. However the data in it does not update by its own, and only updates when I refresh the page, or when I go to another tab and come back.

any ideas how this can be fixed?


Solution

  • If I understand correctly, you need to use setInterval to update the currentTime value. In conjunction with that, you can use a computed property to display the difference in your template.

    It can be something like this:

    new Vue({
      el: "#app",
      data: {
        currentTime: moment(),
        lastUpdatedAt: moment(),
        intervalRef: null,
      },
    
      computed: {
        difference() {
          return moment.duration(this.lastUpdatedAt.diff(this.currentTime)).humanize(true)
        }
      },
    
      mounted() {
        this.intervalRef = setInterval(() => {
          this.currentTime = moment()
        }, 5000)
      },
    
      unmounted() {
        this.intervalRef = null
      }
    })
    <script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <div id="app">
      <h2>Time since last refresh: {{difference}}</h2>
    </div>

    Here, the code updated the time every 5 seconds.

    Moment difference documentation: https://momentjs.com/docs/#/durations/diffing/

    JSFiddle Example