欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue计算属性时v-for处理数组时遇到的一个bug问题

程序员文章站 2022-06-24 17:15:54
问题 bug: you may have an infinite update loop in a component render function 无限循环 1...

问题

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问题,希望对大家有所帮助