获取子组件实例
父组件中:
<template>
<h1>我是 Parent 组件</h1>
<!--子组件-->
<Son ref="vmSon"></Son>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Son, { sonAPI } from './Son.vue'
//获取子组件实例
const vmSon = ref<sonAPI | null>(null)
onMounted(()=>{
console.log('子组件实例:',vmSon.value)
})
</script>
子组件:
<template>
<h3>我是 Son 组件</h3>
</template>
<script setup lang="ts">
// 暴露子组件接口类型
export interface sonAPI {}
</script>
<style scoped>
</style>
使用子组件的变量和方法
子组件中:
import {defineExpose, ref} from 'vue'
// 暴露子组件接口类型
export interface sonAPI {
getName: string,
setName: any
}
let name = ref<string>('seyu')
function setName(lastName: string): string{
return name.value += lastName
}
// 暴露可被外部访问的属性
defineExpose({
getName: name,
setName,
})
父组件:
import { ref, onMounted } from 'vue'
import Son, { sonAPI } from './Son.vue'
//获取子组件实例
const vmSon = ref<sonAPI | null>(null)
onMounted(()=>{
console.log('使用子组件的变量:',vmSon.value?.getName)
setTimeout(()=>{
//调用子组件的方法
let newName = vmSon.value?.setName('Buvelly')
console.log(newName)
},5000)
})