问题
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
})