在vue3中使用composition API,如何在父級(jí)調(diào)用子組件的方法呢,這里我們就需要用到defineExpose,意思是把子組件的方法暴露給父組件。
// parent.vue
<template>
<child ref="childRef" />
<button @click="handleChildFunc">調(diào)用子組件方法</button>
</template>
<script>
import { ref } from 'vue';
const childRef = ref();
const handleChildFunc = () => {
childRef.value.childFunc();
}
</script>
// child.vue
<script>
import { defineExpose } from 'vue';
const childFunc = () => {
// do something...
}
// 暴露給父組件,否則父組件調(diào)用的時(shí)候會(huì)提示找不到childFunc
defineExpose ({ childFunc });
</script>