问题:为什么第一种function(){}就不可以,第二种箭头函数就可以让counter+1?
代码
```html
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<script src="https://unpkg.com/vue@next">script>
head>
<body>
<div id="counter">
Counter:{{counter}}
div>
<script>
const Counter = {
data(){
return{
counter:1
}
},
// 第一种方式
// mounted(){
// setInterval(function(){
// this.counter++
// },1000)
// }
// 第二种方式
mounted(){
setInterval(()=>{
this.counter++
},1000)
}
}
Vue.createApp(Counter).mount('#counter')
script>
body>
html>
```
匿名函数的作用域是全局的,也就是说第一种方式中的this并不指向Counter变量,而是整个script。可以在mounted函数中先获得this再传入,代码可以改成:
mounted(){
var that = this
setInterval(function(){
that.counter++
},1000)
}
而箭头函数没有这个问题,它直接使用mounted的作用域,也就指向了Counter变量
看看控制台有没有错误,有可能是this指向不一致
this指向问题 。因为箭头函数 this 指向 声明它的地方
this指向问题