如何使用Vue3中的ref访问父组件中的子组件方法?

Rob*_*ngh 3 javascript ref typescript vue.js vuejs3

我正在尝试使用 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>
Run Code Online (Sandbox Code Playgroud)

父组件


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>
Run Code Online (Sandbox Code Playgroud)

任何解决方案表示赞赏!

Est*_*ask 11

公共成员应该使用 withdefineExpose语法script setup定义:

defineExpose({ savePaper })
Run Code Online (Sandbox Code Playgroud)

或者使用ctx.expose设置功能

setup(props, ctx) {
  ...
  ctx.expose({ savePaper })
  ...
Run Code Online (Sandbox Code Playgroud)