vue3-学习笔记-获取子组件/dom的ref

1,976 阅读1分钟

1、获取单个组件/dom的ref

注意:父组件调用的子组件的方式,子组件需要通过defineExpose来暴露
父组件

<template> 
    <child ref="childDom" />
    
    <div ref="box">我是DIV</div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import child from './child.vue'

// 子组件
const childDom = ref(null)
onMounted(() => {
    childDom.value.childFn() // 直接调用了子组件的方法   
})

// dom结构
const box = ref(null)
onMounted(() => {
    console.log(box.value) // <div>我是DIV</div>
})

</script>

子组件

<template>
 <div>子组件</div>
</template>

<script setup>
import { defineExpose } from 'vue'

const childFn = () => {
    // ...do something
}

defineExpose({
    childFn
})
</script>

2、获取多个组件/dom的ref

父组件

<template>
        <child v-for="(item, index) in list" :key="index" :ref="{ if (el) childDoms[index] = el }" />
        
        <div v-for="(item, index) in list" :key="index" :ref="{ if (el) divs[index] = el }">1</div>
</template>

<script setup>
    import child from './child.vue'
    import { ref, onMounted } from 'vue'
    // 子组件
    const childDoms = ref([])
    onMounted(() => {
        childDoms.value.map(ele => {
            ele.childFn()
        })
    })
    
    // dom
    const divs = ref([])
    onMounted(() => {
        divs.value.map(ele => {
            console.log(ele) // <div>1</div>
        })
    })
</script>

参考文献: v3.vuejs.org