组合式 API 中 computed 不能用 this,因其在 setup 阶段尚未创建组件实例;应直接访问 ref 或 reactive 声明的响应式变量,如 firstName.value。

在 Vue 3 的 组合式 API(<script setup>)中,computed 里根本不能用 this——因为它压根就是 undefined。这不是 bug,是设计使然:setup 阶段早于组件实例创建,this 还没诞生。所谓“this 指向问题”,本质是误用了选项式 API 的思维去写组合式代码。
选项式 API 中 computed 的 this 指向组件实例
如果你写的是选项式写法(export default { computed: { ... } }),那么:
- 普通函数写法:
fullName() { return this.firstName + this.lastName }→this是当前 Vue 组件实例,可安全访问data、props、其他computed等 - 箭头函数写法:
fullName: () => this.firstName→this指向全局对象(如window)或undefined(严格模式),必然报错
组合式 API 中没有 this,靠变量和作用域链
computed 在组合式 API 里是一个导入的函数,它接收一个 getter 函数作为参数,这个函数内部不依赖 this,而是直接访问其词法作用域中定义的响应式变量:
- 你用
ref或reactive声明的数据,在computed(() => {...})的回调里直接读取,比如firstName.value或user.name - getter 函数的执行上下文由 Vue 内部调度,自动追踪其中访问的响应式属性,无需
this中转 - 错误示范:
computed(() => this.firstName)—— setup 里this是undefined,运行即报错
可写计算属性也要避开 this,用解构或显式引用
当需要 set 逻辑时,依然不碰 this:
- 正确写法:用已声明的
ref或reactive对象,例如
import { computed, ref } from 'vue'
const firstName = ref('张')
const lastName = ref('三')
const fullName = computed({
get() { return firstName.value + lastName.value },
set(val) {
const [first, last] = val.split(' ')
firstName.value = first
lastName.value = last
}
})
</script>
- 关键点:所有赋值/读取都通过已知变量(
firstName、lastName)完成,不引入任何this引用
混用选项式和组合式?小心 this 范围错乱
如果一个组件同时用了 <script setup> 和选项式写法(不推荐),要注意:
- 选项式里的
computed仍走传统this路线,但无法访问<script setup>中定义的局部变量(除非用defineExpose显式暴露) - 组合式里的
computed仍只认自己作用域内的响应式数据,对选项式data或computed一无所知 - 结论:不要混用;统一用组合式,就彻底告别
this困扰

















