Vue3 Composition API问题:函数内访问ref对象报错如何解决?
错误原因与修复方案
错误原因
<script setup>是Vue3 Composition API的语法糖,完全没有this上下文,你代码里的this本身就是undefined,所以访问this.filter会抛出"Cannot read properties of undefined (reading 'filter')"的错误。- 就算有
this可用,你定义的filter是ref响应式对象,脚本里修改它的内部属性必须先通过.value访问,直接操作filter.name也不会生效。
修复代码
假设你原来的错误代码是这样:
<script setup> import { ref } from 'vue' const count = ref(0) const filter = ref({ name: '' }) const increment = () => { count.value++ this.filter.name = 'updated' // 这里触发报错 } </script> <template> <button @click="increment">点击计数</button> </template>
修改后的正确代码:
<script setup> import { ref } from 'vue' const count = ref(0) const filter = ref({ name: '' }) const increment = () => { count.value++ filter.value.name = 'updated' // 直接使用ref变量,通过.value访问内部属性 } </script> <template> <button @click="increment">点击计数</button> </template>
关键要点
- 在
<script setup>中直接使用你声明的响应式变量,永远不要用this。 - 脚本里操作
ref对象的任何值(不管是基础类型还是对象类型),都必须通过.value访问;模板中使用时Vue会自动解包,不需要加.value。
内容的提问来源于stack exchange,提问作者agodoo
相关产品推荐
相关产品推荐

