vue中使用定时器时this指向

箭头函数中的this指向是固定不变(定义函数时的指向),在vue中指向vue;
普通函数中的this指向是变化的(使用函数时的指向),谁调用的指向谁。
 
箭头函数:
1 let timerOne = setInterval(() => {
2     console.log(this);// vue
3 }, 1000); 
4 let timerTwo = setInteval(function () {
5     console.log(this); // window,因为setInterval()函数是window对象的函数
6 }, 1000);
 
1 let timer = setInterval(() => { 
2   this.myFunc();
3 },1000);
4 myFunc(){ 
5   console.log('sunyu is handsome !');
6 }
不用箭头函数也可以搞定:
1 myFunc(){ 
2   console.log(vm.name);// name为已经在created中声明的变量
3 };
4 let  vm = this;
5 let timer = setInteval(function () {
6        myFunc();
7 }, 1000) ;
最后温馨提示不要忘了清除定时器哦!
 

猜你喜欢

转载自www.cnblogs.com/sunyuweb/p/9269481.html