You may have an infinite update loop in a component render function


在写商城项目时写了一段垃圾代码

根据methods返回值,来设置元素的行内样式

//元素:
          <li>
            {{ shop.score[0].name }}
            <i :style="{ color: serviceScore(0) }">{{ shop.score[0].score }}</i>
            <i :style="{ backgroundColor: serviceScore(0) }">{{ score }}</i>
          </li>
          <li>
            {{ shop.score[1].name }}
            <i :style="{ color: serviceScore(1) }">{{ shop.score[1].score }}</i>
            <i :style="{ backgroundColor: serviceScore(1) }">{{ score }}</i>
          </li>

//methods:
    serviceScore(i) {
      let scoreColor = null;
      if (this.shop.score[i].isBetter) {
        this.score = "高";
        scoreColor = "red";
      } else {
        this.score = "低";
        scoreColor = "#6aa44a";
      }
      return scoreColor;
    },        

 

能正常显示,但是console内出现Vue警告

 

测试下来,如果只有一个li,则不会warn,超过一个便会warn

给属性绑定方法的话,Vue会认为你循环操作dom元素,即使你没有循环,他也会发出警告(render - computed - render )

根据网上的说法,我以为是上面的问题,然后我采用笨方法,不使用methods,直接在style内使用三元返回结果,发现问题依旧存在。我把目光转向了双向绑定的score,将其去掉methods,warn消失

          <li>
            {{ shop.score[0].name }}
            <i :style="{ color: serviceScore(0) }">{{ shop.score[0].score }}</i>
            <i :style="{ backgroundColor: serviceScore(0) }">
              {{this.shop.score[0].isBetter ? "高" : "低"}}
            </i>
          </li>
          <li>
            {{ shop.score[1].name }}
            <i :style="{ color: serviceScore(1) }">{{ shop.score[1].score }}</i>
            <i :style="{ backgroundColor: serviceScore(1) }">
              {{this.shop.score[1].isBetter ? "高" : "低"}}
            </i>
          </li>

 

解决方法:

循环一般用来读取数据,而不要改变响应式数据。

根据这个思路,可以把methods或者computed计算完的数据放置于数组中,再在响应式内直接读取数组元素


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM