- 父级组件调用组件的方法,使用 defineExpose
可以通过 defineExpose 暴露子组件的方法,然后在父组件中通过 ref 来调用这些方法。
子组件
<script setup>
import { defineExpose } from 'vue';
// 定义一个方法
const childMethod = () => {
console.log('这是子组件的方法');
};
// 使用 defineExpose 暴露方法
defineExpose({
childMethod
});
</script>
父组件
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const childRef = ref(null);
const callChildMethod = () => {
if (childRef.value) {
childRef.value.childMethod(); // 调用子组件的方法
}
};
</script>
<template>
<ChildComponent ref="childRef" />
<button @click="callChildMethod">调用子组件方法</button>
</template>
- 子组件调用父组件中的方法 使用 provide 和 inject
这种方法适用于多层嵌套的组件结构,其中你想从任何子组件的子组件中访问父组件的方法
父组件
<script setup>
import { provide } from 'vue';
// 定义一个方法并使用 provide 暴露它
const parentMethod = () => {
console.log('这是父组件的方法');
};
provide('parentMethod', parentMethod); // 使用 provide 暴露方法
</script>
子组件
<script setup>
import { inject } from 'vue';
const parentMethod = inject('parentMethod'); // 使用 inject 获取父组件的方法
</script>