【问题标题】:recursive method in Vue JSVue JS中的递归方法
【发布时间】:2026-01-08 14:35:01
【问题描述】:

我试图在 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)
    }

【问题讨论】:

    标签: javascript recursion methods vue.js vue-component


    【解决方案1】:

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

    您可以将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);
    }
    

    【讨论】:

    • 是的,这似乎消除了错误,因为您在我批准的范围内解决了问题。但是,如果我提出超出此答案范围的问题,您介意吗?
    • 您可以随时再次点击“”按钮。但请务必检查之前是否未询问过。
    • 我需要在上述函数中声明前三个变量:var n = $(".item").length; var i = 1; var m = n + 5;,在函数之外,全局,因为这似乎正在阻止方法相应地运行
    • 有什么建议吗?
    • 查看补充答案。