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?
CodePudding user response:
It appears that currentTime
and/or lastRefreshTime
are not reactive - are they properly defined in data with default values set? It should look like this
data () {
return {
currentTime: null,
lastRefreshTime: null
}
}
The values don't have to be null, but it's important that they're defined.
Also, it's best that computed properties return something instead of relying on the default undefined. Honestly I'm not sure that this could cause this issue, but try doing it like this
const minutesSinceLastUpdate = moment... // calculate minutes
return minutesSinceLastUpdate > 5
? minutesSinceLastUpdate
: null
CodePudding user response:
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/[email protected]/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/