Consider the following simplification of the problem I encountered:
export default { data () { return { i_change_alot: 0, }; }, mounted() { setInterval(() => { this.i_change_alot = Math.random(); }, 10); }, computed: { someComputedValue() { this.i_change_alot; return 'a'; } } }
I created an attribute i_change_alot
that changes to a random value every 10 milliseconds. This means that the property becomes extremely reactive, so it will trigger the computed property.
I trigger a dependency (for example purposes) by simply calling this.i_change_alot
, but the result of the computed property never Change.
The end result is that the computed property someCompulatedValue
is updated every 10 milliseconds, which, as far as I know, triggers the view to re-render.
How can I make someCompulatedValue
only re-render when value/result changes?
(The original question was about displaying reactive relative dates, such as "1 second ago", "2 seconds ago", etc. However, after some time this becomes 30 minutes ago code>, < code>31 minutes ago
This means that for a full minute, the string representation has not changed, but it still re-renders every 10 milliseconds due to the dependency on the date attribute).
According to https://github.com/vuejs/vue/issues/11399, I can create a struct with an observer, but it looks counterintuitive.
Why does Vue trigger calculations when the value does not change?
Because Vue will never know if the final result has changed before recalculating. Therefore, the calculated variable will be recalculated every time its dependencies change, which is unavoidable.
A common misunderstanding is that Vue caches calculated variables by calculating the value of the variable, but in fact, Vue caches calculated variables by the state of its dependencies.
Avoid re-rendering too frequently
You can create an observer (as you know) or wrap the template using the calculated value into the component.
Why wrap it into another component help here?
Because Vue will convert your template into a rendering function. The function is recalculated every time its dependencies change. Sound familiar? Yes, it works like a calculated variable. The dependencies of the render function are all the variables you use in the template. So if you wrap frequently changing variables into a component, Vue will only re-render that component and avoid re-rendering your large component. This will have a big impact on your performance