Vue only updates computed properties when the result changes
P粉738046172
P粉738046172 2023-08-25 21:59:19
0
1
542
<p>Consider the following simplification of the problem I encountered: </p> <pre class="brush:js;toolbar:false;">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'; } } } </pre> <p>I created an attribute <code>i_change_alot</code> that changes to a random value every 10 milliseconds. This means that the property becomes extremely reactive, so it will trigger the computed property. </p> <p>I trigger a dependency (for example purposes) by simply calling <code>this.i_change_alot</code>, but the <em>result</em> of the computed property never Change. </p> <p>The end result is that the computed property <code>someCompulatedValue</code> is updated every 10 milliseconds, which, as far as I know, triggers the view to re-render. </p> <p>How can I make <code>someCompulatedValue</code> only re-render when <em>value/result</em> changes? </p> <p>(The original question was about displaying reactive relative dates, such as "1 second ago", "2 seconds ago", etc. However, after some time this becomes <code>30 minutes ago</ code>, < code>31 minutes ago</code> 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). </p> <p>According to https://github.com/vuejs/vue/issues/11399, I can create a struct with an observer, but it looks counterintuitive. </p>
P粉738046172
P粉738046172

reply all(1)
P粉611456309

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template