vue获取DOM方式

文章类型:Vue

发布者:hp

发布时间:2026-05-05

一:引言

在 Vue 中获取 DOM 元素,最推荐且常用的方式是使用 ref 属性。此外,还可以结合生命周期钩子、nextTick 以及原生 JS 方法来实现。

二:方案

1:使用 ref 获取 DOM

v3方式=>定义与模板ref属性同名的ref变量,通过.value访问实际DOM节点,需在onMounted或用户交互后访问,确保DOM已渲染

v2方式=>在模板元素上添加ref属性,在mounted钩子中通过this.$refs.name访问,避免在created阶段访问,此时DOM未挂载


//v3
<template>
  <div ref="myDiv">Hello Vue 3</div>
  <button @click="logDom">获取DOM</button>
</template>

<script setup>
import { ref, onMounted } from 'vue'

// 1. 定义一个ref,初始值为null
const myDiv = ref(null)

// 2. 在组件挂载后访问
onMounted(() => {
  console.log(myDiv.value) // 输出: <div>Hello Vue 3</div>
})

const logDom = () => {
  console.log(myDiv.value)
}
</script>

//v2
<template>
  <div ref="myDiv">Hello Vue 2</div>
</template>

<script>
export default {
  mounted() {
    // 通过 this.$refs 访问
    console.log(this.$refs.myDiv) 
  }
}
</script>

2:获取更新后的最新 DOM (nextTick)


<template>
  <p ref="textRef">{{ message }}</p>
  <button @click="updateAndLog">更新并获取</button>
</template>

<script setup>
import { ref, nextTick } from 'vue'

const message = ref('初始内容')
const textRef = ref(null)

const updateAndLog = async () => {
  message.value = '新内容'
  
  // 此时 DOM 尚未更新
  console.log(textRef.value.innerText) // "初始内容"

  // 等待 DOM 更新完成
  await nextTick()
  
  // 此时可以获取到最新的 DOM
  console.log(textRef.value.innerText) // "新内容"
}
</script>

修改响应式数据后,DOM不会立即更新,使用await nextTick()等待Vue完成DOM刷新,在nextTick之后访问ref.value可获取最新DOM状态

3. 其他获取方式

通过事件对象 (event.target)‌:在事件处理函数中,可以直接通过 event.target 获取触发事件的 DOM 元素。


<template>
  <button @click="handleClick">点击我</button>
  <ul @click="handleListClick">
    <li v-for="item in items" :key="item.id">
      {{ item.name }}
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      items: [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }]
    }
  },
  methods: {
    handleClick(event) {
      // 获取触发点击的按钮元素
      console.log(event.target); 
    },
    handleListClick(event) {
      // 事件委托:获取实际被点击的 li 元素
      if (event.target.tagName === 'LI') {
        console.log('Clicked LI:', event.target.innerText);
      }
    }
  }
}
</script>

‌通过 $el 和查询选择器‌:

this.$el (Options API) 指向组件的根 DOM 元素。可以结合原生方法如 this.$el.querySelector('.class-name') 来查找子元素。


<template>
  <div class="root-container">
    <p class="child-text">Hello</p>
  </div>
</template>

<script>
export default {
  mounted() {
    // 1. 获取组件根元素
    const rootEl = this.$el;
    console.log(rootEl); // <div class="root-container">...</div>

    // 2. 结合 querySelector 查找内部子元素
    const childP = this.$el.querySelector('.child-text');
    console.log(childP.innerText); // "Hello"
  }
}
</script>

‌原生 JS 方法 (document.getElementById 等)‌:可以使用 document.getElementById 或 document.querySelector


<template>
  <div id="app-container">
    <p class="info">Native Query</p>
  </div>
</template>

<script>
export default {
  mounted() {
    // 1. 全局查询(不推荐,可能选到其他组件的元素)
    const globalP = document.querySelector('.info');
    
    // 2. 限定范围的查询(推荐,基于$el)
    const scopedP = this.$el.querySelector('.info');
    
    console.log(scopedP);
  }
}
</script>

三:总结

1:‌生命周期时机‌:不要在 created 或 setup() 同步代码中直接访问 DOM,因为此时组件尚未挂载到页面上,获取到的值为 null。请在 mounted (Options API) 或 onMounted (Composition API) 中访问。

2:‌v-if 的影响‌:如果元素被 v-if 隐藏,对应的 ref 将为 null。只有当条件为真且 DOM 渲染后,ref 才会指向该元素。

‌3:v-for 中的 ref‌:在 Vue 3 中,如果在 v-for 中使用 ref,获取到的将是一个包含所有对应 DOM 元素的数组。


下一篇css盒居中
评论
0条评论遵守法律,文明用语,共同建设文明评论区

暂无评论,快来发表第一条评论吧~