Vue3 v-for绑定的dom获取ref为undefined

这是代码结构

<div class="playerInfo" 
    v-for="(item, index) in data.playersInfo" 
    :key="index" 
    :ref="el => {if(el)playersRef[index] = el}"
    :style="`left:${item.position[0]};top:${item.position[1]}`"
    @click="playerPassHighLight(index)"
>
    <div class="player-name" style="margin-bottom: 5px;">
        {{ item.nameCn }}
    </div>
    <div class="player-avatar">
       <img :src="item.img" alt="" style="width: 60px; height:60px; border-radius: 30px;" />
    </div>
</div> 

然后在console.log(playersRef.value, playersRef.value[0])的时候出现:

playersRef.value有数据,但是playersRef.value[0]为undefined

解决:

参考关于VUE中v-for循环的dom使用ref获取不到问题-CSDN博客

用nextTick再调用一次

onMounted(() => {
   getPassInfo()
   nextTick(()=> getPassInfo())
})

 完美解决~

 P.S. 如果把方法放到updated里面会一直请求数据,就没用updated

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 中,使用 `ref` 可以获取到组件或元素的引用,但是需要注意以下几点: 1. `ref` 只能用在组件和元素上,不能用在普通的 JavaScript 对象上。 2. 组件的 `ref` 是一个字符串,元素的 `ref` 可以是字符串或者函数。 3. 使用 `ref` 获取组件或元素的引用,需要在组件或元素渲染完成后才能获取到。 如果你在 Vue 组件中动态绑定了 `ref`,但是在 `mounted` 钩子函数中获取 `this.$refs[refName]` 的值为 `undefined`,可能是因为获取的时机不正确。 你可以在 `updated` 钩子函数中获取到更新后的 `this.$refs[refName]` 的值,或者使用 `$nextTick` 方法在 DOM 更新后再去获取。例如: ```vue <template> <div ref="myDiv">{{ message }}</div> </template> <script> export default { data() { return { message: 'Hello, World!' } }, mounted() { // 在 mounted 钩子函数中获取 this.$refs.myDiv 的值为 undefined // console.log(this.$refs.myDiv) // 在 updated 钩子函数中获取 this.$refs.myDiv 的值是正确的 // console.log(this.$refs.myDiv) }, updated() { console.log(this.$refs.myDiv) // 输出 div 元素的引用 }, methods: { async changeMessage() { this.message = 'Hello, Vue!' await this.$nextTick() console.log(this.$refs.myDiv) // 输出 div 元素的引用 } } } </script> ``` 如果你在组件中使用了 `v-if` 或者 `v-for` 等指令,需要等到 DOM 更新完成后再去获取引用,否则也会出现获取不到的情况。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值