[英]How can i access child component method in parent component using ref in Vue3?
我正在尝试使用 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>
任何解决方案表示赞赏!
公共成员应该使用带有script setup
语法的defineExpose
定义:
defineExpose({ savePaper })
或者在 设置函数中使用ctx.expose
:
setup(props, ctx) {
...
ctx.expose({ savePaper })
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.