如何用ref获取到DOM元素

201 阅读1分钟

单个元素获取方法:

<div ref='contentRef'> </div>

<script lang='ts' setup>
  onMounted(()=>{
    contentRef.value.style.width='12px';
  })
</script>

循环遍历的元素获取方法

<div v-for='(item,index) in options' :key='index'> 
  <span :ref='el=>{if(el) refItems[index]=el}'>{{item.data}}</span>
</div>
<script lang='ts' setup>
  const refItems=ref<HTMLELEMENT[]>([])
</script>
  • 错误写法:

经实验验证,循环遍历出来的DOM元素一定记得得用数组的形式来存,不能写成:

<div v-for='(item,index) in options' :key='index'> 
  <span ref='contentRef'>{{item.data}}</span>
</div>
// 如果循环遍历的元素被你写成这样,那么你contentRef获取的并不是你当前操作的遍历元素,而是永远是最后一个元素。

使用ref里的dom元素需注意

当你用上面方法获取到对应的DOM元素之后,如果是想使用里面的内容,不能直接在setup里使用,而应该在页面挂载完后使用,即写到onMounted 函数里