vue.js怎么setInterval定时调用方法

methods: {
    A: function() {
        setInterval(function(){ 
            this.B();
        },500)
    },
    B: function() {
        console.log('func B')
    }
}

这样写会报错,怎么实现这样的效果呢?

阅读 17.7k
2 个回答

可以使用箭头函数

methods: {
    A: function() {
        setInterval(() => { 
            this.B();
        }, 500)
    },
    B: function() {
        console.log('func B')
    }
}

或者

methods: {
    A: function() {
        setInterval(this.B, 500)
    },
    B: function() {
        console.log('func B')
    }
}
methods: {
    A () {
        let that = this;
        setInterval(function(){ 
            that.B();
        },500)
    },
    B () {
        console.log('func B')
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题