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

如何在Petite Vue中获取$el DOM元素?

在Petite Vue中正确通过ref获取DOM元素

你遇到的问题是对Petite Vue的$refs用法理解有误,同时错误尝试访问不存在的$el属性。以下是正确的实现方式:

核心要点

  • Petite Vue中,通过ref绑定的元素,在$refs中直接返回原生DOM元素,不需要额外访问$el(这是Vue完整版中组件实例的属性,Petite Vue不存在这个层级)。
  • 必须确保带ref的元素位于v-scope指令管辖的DOM范围内,否则$refs无法捕获到该元素。

修正后的完整代码

HTML部分

<script type="module">
  import { createApp } from 'https://unpkg.com/petite-vue?module'

  createApp({
    count: 0,
    get plusOne() {
      return this.count + 1
    },
    increment() {
      // 直接获取原生DOM元素
      console.log(this.$refs.foobar);
      this.count++
    }
  }).mount()
</script>

<div v-scope>
  <!-- 确保ref元素在v-scope容器内 -->
  <p ref="foobar">{{ count }}</p>
  <p>{{ plusOne }}</p>
  <button @click="increment">increment</button>
</div>

常见错误排查

  1. ref元素不在v-scope范围内:如果你的<p ref="foobar">写在v-scope的div外面,$refs会找不到该元素,必须将其放在挂载的根容器内。
  2. 错误访问$el:Petite Vue的ref绑定的是原生DOM节点,不是组件实例,因此不存在$el属性,直接使用this.$refs.foobar即可操作DOM。

内容的提问来源于stack exchange,提问作者Raf Rasenberg

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:35:33