1. 父组件调用子组件方法
1.1 子组件
在子组件中定义方法,并通过 defineExpose 暴露给父组件。
<template>
<div>子组件</div>
</template>
<script setup lang="ts">
// 定义子组件方法
const doSth = (str: string) => {
console.log("子组件的 doSth 方法执行了!" + str);
};
// 暴露方法
defineExpose({ doSth });
</script>
<style scoped></style>
1.2 父组件
在父组件中通过 ref 获取子组件实例,并调用子组件的方法。
<template>
<button @click="getChild">触发子组件方法</button>
<!-- 定义 ref -->
<HelloWorld ref="childRef" />
</template>
<script setup lang="ts">
import { ref } from 'vue';
import HelloWorld from './components/HelloWorld.vue';
// 定义 ref
const childRef = ref<any>();
// 调用子组件方法
const getChild = () => {
childRef.value.doSth("随便传值!");
};
</script>
<style></style>
2. 子组件调用父组件方法
2.1 子组件
在子组件中通过 defineEmits 定义事件,并触发父组件的方法。
<template>
<div>子组件</div>
</template>
<script setup lang="ts">
import { onMounted } from 'vue';
// 定义事件
const emit = defineEmits(['doSth']);
// 触发事件
const doSth = () => {
emit('doSth');
};
// 组件挂载后触发事件
onMounted(() => {
doSth();
});
</script>
<style scoped></style>
2.2 父组件
在父组件中监听子组件的事件,并定义对应的处理方法。
<template>
<!-- 监听事件 -->
<HelloWorld @doSth="sayHello" />
</template>
<script setup lang="ts">
import HelloWorld from './components/HelloWorld.vue';
// 定义处理方法
const sayHello = () => {
console.log("hello world!");
};
</script>
<style></style>
AI写代码
3. 总结
场景 实现方式 关键点
父组件调用子组件方法 子组件通过 defineExpose 暴露方法,父组件通过 ref 调用 defineExpose, ref
子组件调用父组件方法 子组件通过 defineEmits 触发事件,父组件监听事件并处理 defineEmits, 事件监听
微信扫码加好友
全部评论