当父组件调用子组件的script setup
中的方法时,必须显式导出该方法。因为 script setup
中定义的变量和方法默认是局部的,只有显式导出后,父组件才能访问这些方法。
//父组件-Parent
<template><el-button type="primary" @click="addOrUpdateHandle()">{{ $i18("add") }}</el-button><!-- 弹窗, 新增 / 修改 --><add-or-update ref="addOrUpdateRef"></add-or-update>
</template>
<script setup>
import { unref } from "vue";
const addOrUpdateHandle = (row) => {const instance = unref(addOrUpdateRef);if (instance && typeof instance.init === "function") {instance.init(row);}
};
</script>
//子组件-Child
<template><el-dialogv-model="visible"></el-dialog>
</template>
<script setup>
import { reactive } from "vue";
const state = reactive({visible: false,
});
const init = () => {state.visible = true;
};
// 使用 defineExpose 导出 init 方法
defineExpose({init,
});
</script>