vue3 中 如何获取 遍历拼接ref 的 dom?

items可以通过此方法来获取,但是如何获取 span 标签呢?难道只能id

<template>
  <div v-for="(item, index) in arr" :ref="items">
    <span :ref="item + 'test' " >{{item}}</span>
  </div>
</template>

<script setup>
import {reactive} from 'vue';
const arr = reactive(['a','b','c'])
const items = el => {
  console.log(el);
}
</script>
阅读 5.1k
3 个回答

v-for里,可以使用ref,使用ref操作span,v-for里的ref和普通ref不一样的地方是,在v-for里,ref取到的是个数组,需要使用[0]的方式访问

话说vue不建议直接操作dom

<div v-for="(item, index) in arr" :ref="items" :key="index">
    <span :ref="setRef" >{{item}}</span>
</div>


const arr = ref([1, 2, 3]);
const myRef = ref([]);

const setRef = (el) => {
   myRef.value.push(el);
};

 onMounted(() => {
     console.log(myRef.value)
 })

return {
   arr,
   setRef,
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题