- 将子组件、孙组件的方法使用defineExpose抛出
- 对子组件、孙组件绑定ref属性
- 通过ref属性对组件中抛出的方法进行调用
父组件
<template>
<div>
<Children ref="childrenFn"></Children>
</div>
</template>
<script lang="ts" setup>
import Children from './children.vue';
import { ref, onMounted } from 'vue';
const childrenFn = ref<any>(null);
onMounted(() => {
handleChildren();
});
function handleChildren() {
childrenFn.value.initChildren();
console.log('此处调用子组件的方法');
}
</script>
子组件
<template>
<div>
<Grandson ref="grandsonFn"></Grandson>
</div>
</template>
<script setup>
import Grandson from './grandson.vue';
import { ref, onMounted } from 'vue';
const grandsonFn = ref(null);
function initChildren() {
grandsonFn.value.initGrandson();
console.log('此处调用孙组件的方法');
}
/**
* 将子组件的方法暴露出去
*/
defineExpose({
initChildren,
});
</script>
<style lang="scss" scoped></style>
孙组件
<template>
<div> </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
function initGrandson() {
console.log('此处是孙组件操作');
}
/**
* 将孙组件的方法暴露出去
*/
defineExpose({
initGrandson,
});
</script>
<style lang="scss" scoped></style>