今日在開發新需求時,想說順便把原先沒用 script setup 語法糖的元件,順便加上 script setup,以減少一些不必要的程式碼,結果卻發生父元件抓不到子元件 formRef 的問題。
父元件:
<template>
<q-page>
<SubPage
ref="mainPageRef"
/>
</q-page>
</template>
<script setup>
import {ref} from 'vue';
const mainPageRef = ref(null);
const nextStep = async () => {
const mRef = mainPageRef.value[0];
const isValid = await mRef.formRef.validate();
if (!isValid) return;
}
</script>
子元件:
<template>
<q-form ref="formRef">
<!-- form 表單 -->
</q-form>
</template>
<script setup>
import {ref} from 'vue';
const formRef = ref(null);
// do something
</script>
發生錯誤:
const mRef = mainPageRef.value[0];
// 抓不到 validate
const isValid = await mRef.formRef.validate();
查詢後發現是,假如使用 script setup 語法糖,你不能直接在父元件中訪問子元件的 refs。
所以如果要讓父元件抓到 formRef,子元件需要特別 defineExpose 出去。
defineExpose
是 Vue 3.2 版本中引入的一個新功能,它允許你在使用<script setup>
語法的元件中公開變量或函數,使它們可以在元件的外部被訪問。
<template>
<q-form ref="formRef">
<!-- form 表單 -->
</q-form>
</template>
<script setup>
import {ref} from 'vue';
const formRef = ref(null);
// 加上這行,就正常了
defineExpose({formRef});
// do something
</script>
以前都是直接使用 script setup ,最近在改之前的程式碼才遇到此問題,分享給也正在慢慢開始 script setup 的各位。