Vue3 组件ref实例调用内部方法或属性

Vue2中访问组件内的方法或属性的时候可以直接通过this.$refs.xxx.{prop} this.$refs.xxx.{method}的方式访问,在Vue3中有一些区别

子组件

<script setup>
    const numIndex = ref(0) // 定义一个属性
    const increaseNumIndex = () => { // 定义一个方法
        numIndex.value++
    }

    defineExpose({ // <script setup>模式需要通过defineExpose向外暴露可访问内容
        numIndex,
        increaseNumIndex
    })
</script>

获取组件实例

<template>
    <custom-component ref="ccRef" />
</template>
<script setup>
    import { ref } from 'vue'

    const ccRef = ref(null) // 获取子组件实例时,定义的属性名称要和组件上ref的名字保持一致

    // 此时可以通过实例.value访问子组件暴露的属性或方法
    ccRef.value.increaseNumIndex()
    console.log(ccRef.value.numIndex) 
</script>