[Vuejs]-Infinite loop on v-for loop when trying to execute function inside

0👍

Hi you can fix it this way :

data() {
  return {
    status: 'normal',
    validate: true,
    tmp: 0,
    numberOfItems: 0,
  };
},
methods: {
  addNumberOfItems(number = 1) {
    console.log('It is fired', this.numberOfItems);
    this.numberOfItems += number;
    this.tmp = this.numberOfItems;

    return this.tmp;
  }

In the first addNumberOfItems method you provided, you are assigning the result of this.numberOfItems + number to the tmp data property, which means that the numberOfItems property is not being directly modified. This could be why you are not experiencing an infinite loop when using this method in your template.

In the second addNumberOfItems method, you are directly modifying the numberOfItems property using the += operator, which could potentially trigger a re-render of the template if the numberOfItems property is being used in a way that causes the template to depend on it.

For example, if you have a computed property that depends on numberOfItems, or if you are using numberOfItems in a v-for loop or in a computed class, then modifying the numberOfItems property directly could cause the template to re-render, leading to an infinite loop if not handled properly.

I recommend changing the variable name 🙂

Hope it works for you !

Leave a comment