dom:
<view :animation="barr.animationIndex" v-for="(barr,index) in dataBarrage" :key="index">{{barr.value}}</view>
js:
var _this = this;
for (let i = 0; i < _this.dataBarrage.length; i++) {
var num = Math.random(); //生成随机数
var item = _this.dataBarrage[i];
_this.$set(item, 'x', _this.windowWidth + 200 * num);
_this.$set(item, 'y', num * 100 + 30);
_this.$set(item, 'animationIndex', 'animationAll' + i); //存变量名
//先移到窗口外面的固定位置
_this.animation.translate(item.x, item.y).step({ duration: 10 });
item.animationIndex = _this.animation.export(); //第一次赋值
setTimeout(function() {
_this.animation.translate(-_this.windowWidth - 300, item.y).step();
item.animationIndex = _this.animation.export();
}.bind(_this),1000);
}
我在setTimeout函数里面给item.animationIndex赋值,为什么只有最后一个值生效,前面的 item.animationIndex第一次赋值都是循环后的结果都是正确的,在setTimeout函数里面的时候,给item.animationIndex赋值就只有最后一个生效,是怎么回事呢。应该怎么写呢?
你的这个
item
不是一个局部变量相当于在for
循环外声明 每次赋值都是覆盖 导致最后执行setTimeout
里函数执行的时候读取的是最后一此覆盖的值