Skip to content
Advertisement

Using variable in vue data object for nested loop calculation causes code to break

So i have an object that i want to use in performing some calculations on the sub-objects which it contains before rendering inside a span tag like so:

<span>getTotal(costing_day)</span>

getTotal is a method that does the following:

costing_days.forEach((day) =>{
          day.project_material.forEach((material) => {
             this.total += (parseInt(material.amount) * parseInt(material.quantity));
          });

          day.project_labour.forEach((labour) => {
             this.total += (parseInt(labour.amount) * parseInt(labour.quantity));
          });
          return this.total
      });

And it makes use of the total property declared in my vue data object. But it squawks saying i have an infinite loop in my component,

Now i used a local total variable in the function performing this loop’s calculation like so:

      let total = 0
      costing_days.forEach((day) =>{

          day.project_material.forEach((material) => {
             total += (parseInt(material.amount) * parseInt(material.quantity));
          });

          day.project_labour.forEach((labour) => {
             total += (parseInt(labour.amount) * parseInt(labour.quantity));
          });  
      });

      return total;

And it works fine. Can anyone help me understand why the local variable works while the one in the data object throws an error?

Advertisement

Answer

Vue’s reactivity is handled with getter’s and setter’s, and each change to a set variable immediately fires a re-render.

As suggested in the comments by @aefxx – every time you update this.total it tries to re-render the template, which in turn fires off your method again – causing the infinite loop.

This is why using a local variable fixed it – this.total is never set – all you’re doing is returning a value, and vue renders it.

More info on vue reactivity: https://v2.vuejs.org/v2/guide/reactivity.html

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement