我不明白为什么这段代码有效..
data: {
return {
userMinerals: 0,
mineralsLimit: 1000,
miners: 0,
superMiner: 0,
minerPrice: 10,
superMinerPrice: 100,
minersLimit: 10
}
}
methods: {
counter() {
setInterval(() => {
this.userMinerals += this.miners;
if(this.checkLimit(this.userMinerals, this.mineralsLimit)) {
this.userMinerals = this.mineralsLimit;
}
}, 100);
},
addMiner() {
if (this.userMinerals >= this.minerPrice) {
this.miners += 1;
this.userMinerals -= this.minerPrice;
this.counter();
}
}
}
..但是如果我尝试将参数放入 counter() 中,代码就会停止工作
methods: {
counter(typeOfCredits) {
setInterval(() => {
typeOfCredits += this.miners;
if(this.checkLimit(this.userMinerals, this.mineralsLimit)) {
typeOfCredits = this.mineralsLimit;
}
}, 100);
},
addMiner() {
if (this.userMinerals >= this.minerPrice) {
this.miners += 1;
this.userMinerals -= this.minerPrice;
this.counter(this.userMinerals);
}
}
}
从控制台我可以看到 typeOfCredits 按应有的方式递增,但它不会更新 View 中的值。 谢谢帮助
最佳答案
您不能引用一个参数并期望它在外部发生更改,但您可以传递对可以更改外部某些内容的对象的引用。
var $this = this;
this.counter({
get() { return $this.userMinerals },
set(val) { $this.userMinerals = val }
});
然后像这样在计数器中使用
counter(typeOfCredits) {
setInterval(() => {
typeOfCredits.set(typeOfCredits.get() + this.miners);
if(this.checkLimit(this.userMinerals, this.mineralsLimit)) {
typeOfCredits.set(this.mineralsLimit);
}
}, 100);
},
关于javascript - 带参数和 setTimeout 的 Vue js 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45942038/