关于vue组件中定时器中只能使用箭头函数的问题

vue中使用定时器时this指向

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

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

因此,在vue中要用箭头语法,里面的变量才能使用this指向vue的data数据模型,否则this指向window

箭头函数

methods: {
      goPage: function (index) {
        this.newPage = index
      },
      inv: function () {
        this.invt = setInterval(() => {
          this.goPage(this.nextPage)
          console.log(this)
          //此时的this指向是该vue组件,不管在哪个地方使用,指向都是该vue组件。
        }, 1000)
      }
    }

普通函数

methods: {
      goPage: function (index) {
        this.newPage = index
      },
      inv: function () {
        this.invt = setInterval(function () {
          this.goPage(this.nextPage)
          console.log(this)
          //此时的this并不是该vue组件,而是指向window。
        }, 1000)
      }
    }

此外,在Vue中使用了计时器,一定要记得在生命周期destroyed()里清掉,不然第二次进入这个组件,会出现很大的问题

1   destroyed () {
2     // (很重要)当跳转到其他页面的时候,要在生命周期的destroyed里清空this.cdTimer,不然会出错
3     clearTimeout(this.cdTimer)
4   },

你可能感兴趣的:(关于vue组件中定时器中只能使用箭头函数的问题)