1. 程式人生 > >在做vue計算屬性,v-for處理數組時遇到的一個bug

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

this 解決 就是 com 渲染 fault post return 我想

問題

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

  1. 需要處理的數組(在 ** ssq **裏):
    bonus_code: [‘01‘, ‘19‘, ‘25‘, ‘26‘, ‘27‘, ‘33‘, ‘10‘]
  2. 計算屬性 computed:

    ssqRed: function() {
    return this.ssq.bonus_code.splice(0, 6)
    },
    ssqBlue: function() {
    return this.ssq.bonus_code.splice(6, 7)
    }
  3. 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>
  4. 最終結果我想把數組前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>
  3. 增加的代碼:

    index>5?‘blue-ball‘:‘red-ball‘

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