javascript - 在 Vue3 中,我如何在父組件中使用 ref 訪問子組件的方法?
我正在嘗試使用 Vue3 和 ref 方法在父組件中訪問子組件的方法。但它返回了一個錯誤。
未捕獲的類型錯誤:addNewPaper.value?.savePaper 不是一個函數
以下是我的程式碼。請指導我哪裡有錯。
子元件
<script setup lang="ts">
import { useWindowScroll } from '@vueuse/core'
import { Notyf } from 'notyf'
import { computed, defineProps, reactive, ref } from 'vue'
import { papers } from '/@src/firebase/connections'
const companySize = ref('')
const businessType = ref('')
const productToDemo = ref('')
const date = ref(new Date())
const { y } = useWindowScroll()
const isStuck = computed(() => {
return y.value > 30
})
const initialState = reactive({
subject: '',
paper: '',
marks: '',
})
const notyf = new Notyf()
const props = defineProps({
subjects: { required: true },
})
const savePaper = () => {
papers
.add(initialState)
.then(() => {
notyf.success('Paper saved successfully')
})
.catch((err) => {
notyf.error('Something went wrong')
})
}
</script>
父組件
const addNewPaper = ref()
const successSave = () => {
addNewPaper.value?.savePaper()
notyf.success('Your paper has been successfully created!')
}
<template #content>
<FormAddNewTopical ref="addNewPaper" :subjects="_subjects"></FormAddNewTopical>
</template>
任何解決方案都感激!
答案#1
公共成員應該使用 script setup 語法搭配 defineExpose 定義:
defineExpose({ savePaper })
或者在 setup 函數中使用 ctx.expose:
setup(props, ctx) {
...
ctx.expose({ savePaper })
...
