2025/4/25
向
示例
一个例子------计数器,通过this来操作数据。
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<title>回调函数中的this</title>
</head>
<body>
<div id="app">
<h1>{{msg}}</h1>
<h1>计数器:{{count}}</h1>
<button @click="addOne">加一</button>
</div>
<script>
new Vue({
el : "#app",
data:{
msg: "回调函数中的this",
count:0
},
methods:{
addOne(){
this.count++
}
}
})
</script>
</body>
</html>
Vue(vm) 和 this的关系
html
methods:{
addOne(){
this.count++
console.log(this === vm)
}
}

所以不难发现。其实vm(vue实例对象) 和this是一个东西,所以其实我们也可以使用
html
vm.count++
来实现,但是一般更加常使用this。this就是vm,vm可以访问count通过数据代理。
箭头函数
html
<body>
<div id="app">
<h1>{{msg}}</h1>
<h1>计数器:{{count}}</h1>
<button @click="addOne1">加一1</button>
<button @click="addOne2">加一2</button>
</div>
<script>
const vm = new Vue({
el : "#app",
data:{
msg: "回调函数中的this",
count:0
},
methods:{
addOne1(){
this.count++
},
addOne2:()=>{
this.count++
}
}
})
</script>
</body>
当使用箭头函数之后,计数器失效。因为箭头函数中没有this,箭头函数中的this是从父级作用域当中继承过来的。对于当前程序来说,父级作用域是全局作用域:window。
普通函数的
this
指向取决于函数的调用方式。当函数作为对象的方法调用时,this
指向该对象;在全局作用域中调用函数,this
指向全局对象。addOne1是一个普通函数,能够根据调用方式来决定this的指向,上述的调用是作为Vue实例对象的方法调用 ,所以this指向该Vue实例。但箭头函数不具备自己独立的
this
绑定,它的this
是在定义时从父级作用域继承而来的,且不会被调用方式影响。addOne2
箭头函数定义于methods
对象里 ,不过methods
对象本身并非一个函数作用域 ,所以**addOne2
的父级作用域就是全局作用域**。而全局作用域中并没有属性count。
所以在methods中尽量的不使用箭头函数,我们常需要在回调函数中使用到this和vm实例。
