問題
bug: You may have an infinite update loop in a component render function 無限循環
- 需要處理的數組(在 ** ssq **里):
bonus_code: ['01', '19', '25', '26', '27', '33', '10']
- 計算屬性 computed:
ssqRed: function() {
return this.ssq.bonus_code.splice(0, 6)
},
ssqBlue: function() {
return this.ssq.bonus_code.splice(6, 7)
}
- 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>
- 最終結果我想把數組前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會對原數組造成改變。
在尋找解決方案時,朋友少暉教給我一種更好的解決方式,很感謝
即類名判斷
- 如果數組大小已知,就做一個類名判斷,索引大於多少展示藍色的類名就行了;
- 處理后的 html代碼:
<em v-for="(item, index) in ssq.bonus_code" :class="['tac','mr5','fl',index>5?'blue-ball':'red-ball']" >{{ item }}</em>
- 增加的代碼:
index>5?'blue-ball':'red-ball'