在vue中如果你执行了如下代码
this.name=1
this.name=2
this.name=3
他不会执行三次赋值,而是直接执行了最后一步,因为同一个tick中相同watcher会缓冲起来只执行最后一个
class Buffer {
constructor() {
this.buffers = []
this.status = 0
}
exe(action) {
this.buffers.push(action)
if (this.status === 0) {
Promise.resolve().then(() => {
this.buffers.pop()();
this.buffers.length = 0
this.status = 0;
})
}
this.status = 1
}
}
const buffer = new Buffer()
setTimeout(() => { // 这里模拟了下一个tick,所以会执行
buffer.exe(function () {
console.log(444444444);
})
}, 0);
buffer.exe(function () { // 同一个tick,缓存起来,但不会执行
console.log(11111);
})
buffer.exe(function () {// 同一个tick,缓存起来,但不会执行
console.log(222222);
})
buffer.exe(function () { // 同一个tick,,缓存起来,只会执行这一步
console.log(333333333333);
})