[Vuejs]-Why is self multiplying returning rediculously large number?

3👍

There’s a vital lesson in this! Vue updates your page to reflect changes in your model. If rendering your page causes a change in your model (that causes Vue to re-render the page), then you have created an infinite loop – hence your very big number.

The moral of the story is that you don’t know and shouldn’t care when or how often your templates are rendered. You create the bindings such that your page reflects your model as you wish, then you leave Vue to take care of it. In practice, never call methods from a render function. Render functions should use data, injects, props, computed, perhaps watch: anything that’s reactive. Methods should be used for responding to user activity and processing it back into the model.

1👍

You’re running in to an infinite loop…

  1. You call mulBy3() in your template
  2. This mutates the num data property
  3. This triggers a redraw
  4. Goto #1

What you should do instead is use a computed property, eg

computed: {
  mulBy3 () {
    return this.num * 3
  }
}
<p>3 times num = {{ mulBy3 }}</p>

This will react to changes to num.

For more reasons why you should not call methods in your templates, see https://v2.vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods

👤Phil

Leave a comment