Vue父组件使用v-for循环子组件ref使用问题

问题

Vue+Vite项目,vue某个组件基于<script setup lang="ts"> 形式编程方式,父组件中循环渲染子组件成功,但是使用ref获取子组件实例时,获取失败。

如下异常示例:

//template 父组件使用v-for循环引用子组件reply
<reply ref="commentReplyRef" @closeOtherCommentBoxExcept="closeOtherCommentBoxExcept"
v-for="(reply, idx) in replyList" :key="idx" :reply="reply" :index="idx as number"/>

//<script setup lang="ts"> 脚本中定义变量
let commentReplyRef = ref();//commentReplyRef.value是undefined
//let commentReplyRef = ref([]); //commentReplyRef.value是空数组对像
//let commentReplyRef = ref(null);//commentReplyRef.value是 null

//在子组件绑定的方法中使用 commentReplyRef 
const closeOtherCommentBoxExcept = (index) => {
  console.log(commentReplyRef.value);
  nextTick(() => {
    commentReplyRef.value.forEach((replyItem, idx) => {
      if (index != idx) {
        console.log(replyItem)
        replyItem.hideCommentBox()
      }
    })
  })
}

上述示例中的写法,即使放在onMounted({}) 中去获取也获取不到。

实际情况看起来是,变量commentReplyRef 虽然定义了,但是组件渲染完成后没有被赋值。

解决方法

修改如下  

//template 父组件使用v-for循环引用子组件reply,同时给数组添加元素
<reply :ref="(e)=>{if(e)commentReplyRef.push(e)}" @closeOtherCommentBoxExcept="closeOtherCommentBoxExcept"
v-for="(reply, idx) in replyList" :key="idx" :reply="reply" :index="idx as number"/>

//<script setup lang="ts"> 脚本中定义变量
let commentReplyRef = ref([]); //定义为数组形式


const closeOtherCommentBoxExcept = (index) => {
  console.log(commentReplyRef.value);
  nextTick(() => {
    commentReplyRef.value.forEach((replyItem, idx) => {
      if (index != idx) {
        console.log(replyItem)
        //调用单个子组件中的函数
        replyItem.hideCommentBox()
      }
    })
  })
}

其中 hideCommentBox()是子组件定义的函数,需要使用defineExpose 暴露出来父组件才能访问

const hideCommentBox = () => {
  commentBoxShow.value = false
}
defineExpose({
  hideCommentBox
})

参考:

vue3 通过动态 ref 获取 v-for 中的组件_vue3 组合式 怎么拿到vfor渲染的组件实例-CSDN博客

vue.js实现带表情评论功能前后端实现(仿B站评论)_vue评论模块-CSDN博客

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值