3

I am trying to access the child method in the parent component using vue3 and ref method. But it returns an error.

Uncaught TypeError: addNewPaper.value?.savePaper is not a function

Below is my code. Please guide me where i am wrong.

Child component

<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>

Parent component


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>

Any solution appreciated!

1 Answer 1

11

Public members are supposed to be defined with defineExpose with script setup syntax:

defineExpose({ savePaper })

Or with ctx.expose in setup function:

setup(props, ctx) {
  ...
  ctx.expose({ savePaper })
  ...
Sign up to request clarification or add additional context in comments.

10 Comments

I am trying to use the same but it throws an error Module '"vue"' has no exported member 'defineExpose'.Vetur(2305)
Check the linked documentation, it shows that define functions don't need to be imported, they are parts of script setup syntax. I'm quite sure that defineExpose is compiled to ctx.expose then.
Cannot find the name defineExpose. This is the error now coming. Also same for ctx
Where does the error come from? Does the app compile? You listed Vetur error previously that can behave differently
@RobinSingh Please, specify the exact errors. There's a big difference if it comes from a compiler or an editor, and if it comes from TS at compilation time or JS at runtime. Make sure you use the latest Vue version. Also check stackoverflow.com/a/69999044/3731501
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.