defineExpose คือการที่ตัว Parent จะเข้าไปดึงค่าตัวแปร หรือฟังก์ชั่นจาก Child Component อ่ะแหละ แล้วทำถูกตั้งนานมันก็ดึงไม่ได้ซะที เลยไปค้นหาเจอว่ามีคนติดตั้งแพคเกจ @vue/complier-sfc แล้วหาย
โดนหลอกไปวูบนึง
คือหลังจากติดตั้งแพคเกจแล้ว รีรันเซิร์ฟเวอร์แล้ว มันก็ยังใช้ไม่ได้ แล้วมันก็ผ่านไปสัก 5 นาที มันก็ดึงได้ อ้าว ตกลงได้ตอนไหน ยังไง 555+ สรุปว่ามันได้เพราะอันนี้แหละ เพราะจริงๆ คือโค้ดเขียนถูกตั้งแต่แรกแล้ว
มาดูวิธีใช้ defineExpose กันหน่อย
// components/ChildComponent.vue
<script setup>
const data = [];
const a = ref('a');
const b = 'b';
const hello = () => {
console.log('hello function');
};
defineExpose({
data,
a,
b,
hello
})
<script>
<template>
{{ a }} is {{ b }}
</template>
// pages/index.vue
<script setup>
const childComponent = ref();
onMounted(() => {
console.log(childComponent.value.data);
console.log(childComponent.value.a);
console.log(childComponent.value.b);
console.log(childComponent.value.hello());
});
<script>
<template>
<ChildComponent ref="childComponent" />
</template>
