在做vue計算屬性,v-for處理數組時遇到的一個bug


問題

bug: You may have an infinite update loop in a component render function 無限循環

  1. 需要處理的數組(在 ** ssq **里):
bonus_code: ['01', '19', '25', '26', '27', '33', '10']
  1. 計算屬性 computed:
ssqRed: function() {
    return this.ssq.bonus_code.splice(0, 6)
},
ssqBlue: function() {
    return this.ssq.bonus_code.splice(6, 7)
}
  1. v-for 代碼:
<em class="red-ball tac mr5 fl" v-for="(item, index) in ssqRed">{{ item }}</em>
<em class="blue-ball tac mr5 fl" v-for="(item, index) in ssqBlue">{{ item }}</em>
  1. 最終結果我想把數組前6個數渲染成紅色球,最后一個(也就是第7個)渲染成藍色。

解答

我已經在 SegmentFault上提問,地址:vue計算屬性computed同時操作一個數組

我已采納答案,將代碼改成:

ssqRed: function() {
    return this.ssq.bonus_code.slice(0, 6)
},
ssqBlue: function() {
    return this.ssq.bonus_code.slice(6, 7)
}

問題就在於自己沒搞清楚 splice會對原數組造成改變。

在尋找解決方案時,朋友少暉教給我一種更好的解決方式,很感謝

即類名判斷

  1. 如果數組大小已知,就做一個類名判斷,索引大於多少展示藍色的類名就行了;
  2. 處理后的 html代碼:
<em v-for="(item, index) in ssq.bonus_code" :class="['tac','mr5','fl',index>5?'blue-ball':'red-ball']" >{{ item }}</em>
  1. 增加的代碼:
index>5?'blue-ball':'red-ball'


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM