[英]VueJS - V-for doesn't re-render after data is updated and needs page refresh to see the change
[英]VueJS doesn't re-render until loop is finished
我有這段VueJS代碼:
new Vue({
el: '#app',
data: {
tiles: [
{ isActive: false },
{ isActive: false },
{ isActive: false },
{ isActive: false },
{ isActive: false }
]
},
methods: {
startWithLoop: function() {
console.log("startWithLoop");
for(var i = 0; i < 10000; i++ ) { this.blink() };
},
startWithInterval: function() {
console.log("startWithInteral");
setInterval(this.blink);
},
blink: function(){
console.log("blink");
var index = Math.floor(Math.random() * this.tiles.length);
this.tiles[index].isActive = !this.tiles[index].isActive;
}
}
})
如果我調用該方法startWithInterval
我可以在視圖如何看tiles
正在改變狀態的所有時間。
如果我調用方法startWithLoop
,則在循環完成之前,視圖中看不到任何更改。
這是JSFiddle
如何在循環的每個步驟中觸發視圖更改?
不,這是Javascript eventloop在瀏覽器中的工作方式(不僅如此)。
您可以想象Javascript只在“瞬間之間的間隔”中執行,因此您對瀏覽器中發生的情況的了解只是瞬間的快照。
您可以編寫類似於setTimeout
類似於loop的內容,以使Vue注意到更改,然后將其推送到DOM。
beforeDestroy() {
if (this.timeout != null) {
clearTimeout(this.timeout);
this.timeout = null;
}
},
startWithLoop: function() {
console.log("startWithLoop");
let i = 0
const iter = () => {
this.blink();
i += 1;
if (i < 10000) {
this.timeout = setTimeout(iter);
}
}
iter();
},
處理上面的更改: https : //jsfiddle.net/ssorallen/9pqscat1/3/
總結並結合所有建議,我了解到:
因此,您必須將循環的迭代移至另一個進程。 我當時以為promise可以解決,但更簡單的方法是使用setTimeout()
而不使用延遲參數。
所以代替這個:
for(var i = 0; i < 10000; i++ ) {
this.blink()
};
我的代碼如下所示:
for(var i = 0; i < 10000; i++ ) {
setTimeout(this.blink)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.