<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<p>{{msg}}</p>
<button @click = 'start'>start</button>
<button @click = 'stop'>stop</button>
<p>{{intervalId}}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el : '#app',
data : {
msg : '这是一段用来测试的文字~~~~',
intervalId: null,
},
methods : {
start (){
//console.log(this.msg);// start函数中还可以访问this.msg
if(this.intervalId != null){return};
//终止当前函数并返回当前函数的值
const a = this;
// this.intervalId = setInterval(()=>{
this.intervalId = setInterval(function(){
//console.log(this.msg);
//如果用的是function定义函数,并且用this.msg获取数据,就已经是undefined了,因为this指向发生变化
// 方法一 使用箭头函数
// 方法二 在进入该计时器的function之前,把this的指向保存为一个变量,然后调用
const head = a.msg.substring(0,1);
// 截取字符串0-1位置(第一个字)+ 字符串第二个字以后的字直至结尾
const end = a.msg.substring(1);
console.log(head,end);
this.msg = end + head;
},800
);
},
stop(){
clearInterval(this.intervalId);
this.intervalId = null;
// 清除定时器后归为null
}
}
})
</script>
</body>
</html>
箭头函数没有自己的this, 它的this是继承而来; 默认指向在定义它时所处的对象(宿主对象),而不是执行时的对象, 定义它的时候,可能环境是window;
箭头函数可以方便地让我们在 setTimeout ,setInterval中方便的使用this。
箭头函数中的this指向是固定不变(定义函数时的指向),在vue中一般指向vue
普通函数中的this指向是变化的(使用函数时的指向),谁调用的指向谁