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

Vue 3中为何无法通过变量访问this.$refs.toLocation?

在Vue 3中通过动态变量访问$refs元素的解决方案

核心解决方法

Vue 3中this.$refs是普通JavaScript对象,要通过变量值访问对应ref元素,必须使用方括号语法——点语法会直接寻找与变量名同名的ref,而非变量存储的值。

比如你定义const toLocation = 'interesse',正确访问方式为:

const targetElement = this.$refs[toLocation]

针对你遇到的问题逐个解决

1. Options API下的动态访问示例

如果使用Vue 3的Options API写法,直接在方法中使用方括号语法即可:

export default {
  methods: {
    accessTargetRef() {
      const toLocation = 'interesse'
      // 动态获取对应ref元素
      const targetRef = this.$refs[toLocation]
      // 确保元素存在后再执行操作
      if (targetRef) {
        // 示例:滚动到该元素位置
        targetRef.scrollIntoView({ behavior: 'smooth' })
      }
    }
  }
}

2. 解决'ref is not defined'错误

你尝试const toLocation = ref('Vue.js')时报错,是因为未导入Vue的ref函数。Vue 3的Composition API中,所有响应式API都需要从vue包显式导入:

// 必须先导入ref函数
import { ref } from 'vue'

const toLocation = ref('interesse')

3. Composition API(

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:37:20