S
S
Sergey Sokolov2019-02-26 15:19:48
Vue.js
Sergey Sokolov, 2019-02-26 15:19:48

How to force a computed property to be recalculated on a timer?

The component displays the time of the last update: "just now", "a minute ago", "5 minutes ago", "yesterday" and so on. propsThe timestamp of its update is transmitted to it through tsit, and then it itself.
The displayed calculated human-readable "5 minutes ago" needs to be updated. Immediately after the update once a minute. Then once every 15 minutes, an hour and then .. and then you can once an hour, it's not a pity.
I can't figure out how to properly force this property to be updated. By default, it is calculated once when rendering the component and then sits quietly, because. tsdoes not change, there is no reason to recalculate.
What have you tried. Added data-propertynow, which does not participate in anything, because in fact, these lines “5 minutes ago” are considered in a separate module based on the current time passed there tsand which the module itself knows how to find out. The first time the computed property is called, I run setTimeout(), which will update the data property now. But Vue is cleverly optimized! If this property is not used in any way in a computed property, then no update (call) occurs.
It is worth adding console.log(this.now)to the body of the calculation. Saint-va, like cheers, everything is ticking properly. But in production, everything is console.*cut out and updates will be lost. Yes, and in general this is some kind of crutch.
So how do I use the worthless data property, or otherwise cause the computed to be updated?
Shortened example:

import ago from '@/utils/ago';

export default {
  props: {
    ts: Number,
  },

  data: () => ({
    now: Date.now(),
  }),

  computed: {
    lastUpdated: function() {
      console.log("[lastUpdated]", this.now); // так обновляется
      // console.log("[lastUpdated]"); // а так не обновляется

      const that = this;
      setTimeout(() => that.now = Date.now(), 5000);
      
      return ago(this.ts);
    }
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Proskurin, 2019-02-26
@Vlad_IT

Instead of console.log(this.now) even var temp = this.now will work, because computed property, it's a "tricky" getter. And why not create a property string in data - lastChanges, and change it on a timer? Example https://jsfiddle.net/4zy10xoh/2/

L
levchak0910, 2019-02-27
@levchak0910

It will be useful

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question