Vue中使用setinterval定时器里this的指向

箭头函数中的this指向是固定不变(定义函数时的指向),在vue中指向vue;

普通函数中的this指向是变化的(使用函数时的指向),谁调用的指向谁。

例如两个定时器

      const myTimer1 = setInterval(function () {
        console.log(this)
        console.log(this.showLoadingOpen)
        clearInterval(myTimer1)
      }, 1000)
      const myTimer2 = setInterval(() => {
        console.log(this)
        console.log(this.showLoadingOpen)
        clearInterval(myTimer2)
      }, 1000)

其中showLoadingOpen是在vue的data中定义的一个bool类型值,运行后结果如下:

 最后请记得关闭定时器clearInterval(myTimer)

猜你喜欢

转载自blog.csdn.net/wangyuntuan/article/details/123107680