什么是 defineExpose()?
defineExpose() 是 Vue 3 提供的一个 Composition API 函数,用于明确指定哪些内部响应式状态或函数可以被外部访问。
如何使用 defineExpose()?
在子组件中定义:
const submit= () => {
const result = A({
接口传参数据
});
const res = B({
接口传参数据
});
return Promise.all([result, res]).then((values) => {
const bol = values.every((item) => {
!item.success && msg.error(item.message);
return item.success;
});
return bol;
});
};
defineExpose({
submit,
});
注意:defineExpose() 应该放在末尾,因为任何在它之后声明的变量或函数都不会被自动包含在暴露的对象中。
在父组件中访问:
<modal>
<组件名 ref="syncRef" />
<template #footer>
<n-button-primary @click="submit">确定</n-button-primary>
</template>
</modal>
import 组件名 from './components/组件名文件位置.vue';
const syncRef = ref<InstanceType<typeof 组件名> | null>(null);
const handleSubmitSync = async () => {
const result = await syncRef.value?.submit();
result;
};