You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3 Composition API问题:函数内访问ref对象报错如何解决?

错误原因与修复方案

错误原因

  1. <script setup>是Vue3 Composition API的语法糖,完全没有this上下文,你代码里的this本身就是undefined,所以访问this.filter会抛出"Cannot read properties of undefined (reading 'filter')"的错误。
  2. 就算有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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:30:56