我试图在Vue中调用一个方法,但是我得到了以下错误
this.loop不是一个函数。(在“this.loop()”中,“this.stagger”未定义)
以下是一种方法:
loop: function () {
var n = $(".item").length;
var i = 1;
var m = n + 5;
setTimeout( function () {
$('.item:nth-child('+i+')').addClass('show');
var x = i - 2;
var y = x - 2;
i = i + 3;
// for 2 columns:
// x = i - 1;
// i = i + 2;
$('.item:nth-child('+x+')').addClass('show');
$('.item:nth-child('+y+')').addClass('show'); // remove for 2 columns
if (i < m) {
this.loop() // error occurs here
}
}, 100)
}发布于 2018-02-25 08:09:43
这是因为this不再在setTimeout的回调函数中引用对象。有几种解决办法。
您可以将function更改为箭头函数:
setTimeout( () => {这样,this将保留它的原始值,也在回调中。
或者,可以将this绑定到函数:
setTimeout( function () {
// ...
}.bind(this), 100)
//^^^^或者,您可以复制this并使用它:
var that = this;
setTimeout( function () {
// ...
that.loop();
// ...
}, 100)避免重新初始化
目前,递归调用还将重置变量,包括i。
通过传递i作为参数来解决这个问题:
loop: function (i = 1) { // <<---- default value
var n = $(".item").length;
var m = n + 5;
if (i >= m) return; // <<-----
setTimeout(() => {
$('.item:nth-child('+i+')').addClass('show');
var x = i - 2;
var y = x - 2;
$('.item:nth-child('+x+')').addClass('show');
$('.item:nth-child('+y+')').addClass('show');
this.loop(i+3); // <<------
}, 100);
}https://stackoverflow.com/questions/48971512
复制相似问题