vue2.0
官方文档中已说明:
计算属性将被混入到
Vue
实例中。所有getter
和setter
的this
上下文自动地绑定为Vue
实例。注意如果你为一个计算属性使用了箭头函数,则this
不会指向这个组件的实例,不过你仍然可以将其实例作为函数的第一个参数来访问。
1 两种函数方式调用 this
的结果
1.1 一般函数
computed: {
aDouble: function() {
console.log(this) // 输出 vue 实例
return this.a * 2
},
aPlus: {
get: function() {
console.log(this) // 输出 vue 实例
return this.a + 1
},
set: function(val) {
console.log(this) // 输出 vue 实例
this.a = val - 1
}
}
}
输出结果都为 Vue
实例:
1.2 箭头函数
computed: {
aDouble: () => {
console.log(this) // 输出 undefined
return this.a * 2 // 这里由于 this 为 undefined , 所以调用 a 会报错
}
}
输出结果为 undefined
,调用 this.a
报错:
因此在箭头函数中调用
this
会导致错误!
2 在箭头函数中巧用 this
虽然无法直接在箭头函数中使用 this
,但是 vue2.0
给 computed
中的箭头函数提供了一个接口,即第一个引入的参数就是 vue
实例。
computed: {
aDouble: (vm) => {
console.log(vm) // 输出 vue 实例
return vm.a * 2 // 可以正常调用 a
},
path: (vm) => vm.$router.currentRoute.path // 通过第一个参数 vm 代替 this,可以调用 $router
}
3 在 Vue 3.0
中
都说到这了,再扩展一下 Vue 3.0
的 computed
使用情况。
Vue 3.0
中的 <script setup>
,使用过的都知道在 setup
里调用数据、函数方法等是不用 this
的,所以箭头函数的使用更得心应手了(不用考虑 this
飞了!)。
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
let a = ref(1)
computed: {
aDouble: () => a.value * 2 // a 可以不用 this 直接调用
path: () => router.currentRoute.path // vue-router 在 vue3 中的使用也不一样了
}
</script>
总结
总结一下 computed
中 this
的使用:
vue2.0
中function() {}
内可以直接使用this
,指向的是vue
实例;vue2.0
中(vm) => {}
内不能直接使用this
,要用第一个参数vm
代替作为vue
实例;vue3.0
setup()
不需要this
,可以直接调用数据、函数方法等。
笔记主要为自用,欢迎友好交流!