一、用法
- defineExpose用于子组件的属性和方法暴露,父组件可以通过ref标记子组件来获取子组件暴露的方法和属性,子组件通过defineExpose方法暴露出来后,父组件才可以获取到
二、示列
- 子组件
<template>
<div class="">
<h1>我是子组件</h1>
</div>
</template>
<script lang="ts" setup>
import { ref, defineExpose } from 'vue';
const a = ref<string>('我是子组件暴露的属性');
const sonMethod = () => {
console.log('我是子组件暴露的方法');
};
defineExpose({
a,
sonMethod
});
</script>
<style lang="scss" scoped></style>
- 父组件用ref来标记.value的形式来获取
<template>
<div class="">
<h1>我是父组件</h1>
<som ref="somRef"></som>
</div>
</template>
<script lang="ts" setup>
import som from './son.vue';
import { ref, onMounted } from 'vue';
const somRef = ref(null);
//必须在onMounted生命周期里面才能拿到
onMounted(() => {
console.log('somRef', somRef.value.a); //somRef 我是子组件暴露的属性
});
</script>
<style lang="scss" scoped></style>