Vue JS中的递归方法

Rob*_*man 2 javascript methods recursion vue.js vue-component

我试图在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)
    }
Run Code Online (Sandbox Code Playgroud)

tri*_*cot 8

这是因为this在的回调函数中不再引用该对象setTimeout。有几种解决方案。

您可以将更function改为箭头功能:

setTimeout( () => {
Run Code Online (Sandbox Code Playgroud)

这样this,即使在回调中,也将保留其原始值。

或者,您可以绑定this到该函数:

setTimeout( function () {
    // ...
}.bind(this), 100)
//^^^^
Run Code Online (Sandbox Code Playgroud)

或者,您可以复制this并使用它:

var that = this;
setTimeout( function () {
    // ...
    that.loop();
    // ...
}, 100)
Run Code Online (Sandbox Code Playgroud)

避免重新初始化

目前,您的递归调用还将重置变量,包括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);
}
Run Code Online (Sandbox Code Playgroud)