vue中使用setInterval需要注意

methods:{
    myclick:function(){
        setInterval(function(){
            console.log('===='+this.message);
        },1000)
    }
},            

这样的结果就是获取不到this.message的值。原因是setInterval()函数中的 this 指向的并非vue对象,而是指向window对象,所以就获取不到this.message的值。参考:https://www.jb51.net/article/147364.htm

处理方法:

使用另一种写法就能获取值了

methods:{
    myclick:()=>{
        setInterval(function(){
            console.log('===='+this.message);
        },1000)
    }
},  

结果

猜你喜欢

转载自www.cnblogs.com/masha2017/p/12208383.html