Vue中如何使用定时器
created() {// 如果不加 window ,则会使用 vue实例的方法,将无法清除定时器this.timer = window.setInterval(() => {// 要执行的函数this.init()}, 5000)},beforeDestroy() {window.clearInterval(this.timer)this.timer = null},
网友提供:
- vue组件中,this指向实例,【实例中重写了setInterval等一整套方法】。所以,千万不能和 window 下挂载的方法混用
- 具体不同在于,window.setInterval执行完比后返回一个id,而vue实例中返回【定时器对象】,当然该对象中包含一个_id的私有属性
- 因为 clearInterval 方法参数是id,所以最佳实践是统一使用 window 的方法,不要使用 vue组件的方法
- vue中的定时器方法,要使用箭头函数,不要出现 const that = this 的写法
附:箭头函数改写普通函数方法
this.timer = setInterval(function(){this.setState({date:new Date()})
}.bind(this),1000)