Is there a way to access a child component's method from the parent component using ref in Vue3?

I am encountering an issue while attempting to call the child method from the parent component in vue3 using the ref method. Unfortunately, an error is being thrown.

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

Displayed below is my code. I would be grateful for any guidance on where I might have made a mistake.

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 assistance would be highly appreciated!

Answer №1

It is recommended that public members be declared using the defineExpose function in combination with the script setup syntax:

defineExpose({ savePaper })

Alternatively, they can be exposed using ctx.expose within the setup function:

setup(props, ctx) {
  ...
  ctx.expose({ savePaper })
  ...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Access an external URL from JSON data simply by utilizing VueJS

I am currently facing a challenge with linking to external URLs. The URL is extracted from JSON and connected to an HTML tag, but I am unable to retrieve the data and link it to the URL when clicking on images. HTML <section class="bg-light page-secti ...

Issue with Tooltipster plugin causing jQuery function not to trigger upon clicking the link within the tooltip

Recently, I've been experimenting with a jquery plugin called Tooltipster by inserting some HTML into the tip with an href link. The problem arises when I try to add a class to the href and fire a jquery function upon clicking it. No matter how much I ...

Getting data from an HTML file with AJAX

I have a JavaScript application where I am trying to retrieve an HTML file in order to template it. Currently, I am using the following method: var _$e = null; $.ajax({ type: "GET", url: "/static ...

Recognizing mouse and keyboard inputs within an Angular application when using ng-repeat

In my application, I am dynamically generating a series of spans using ng-repeat, with each span having a unique id (e.g. span-{{$index}}). Now, I am looking to implement the following functionality: When clicking on a span, I want to copy the id of that ...

Limiting ng-repeat in AngularJS when the last item on the object is reached

I have a large object being repeated using ng-repeat, and it runs smoothly on Chrome and Opera. However, when it comes to browsers like Mozilla and IE, the performance is very slow. I tried implementing pagination, which helped speed things up, but ideally ...

I can't seem to establish a connection with my MongoDB Atlas cluster. I encountered the MongooseError, which is as follows:

Error [MongooseError]: The uri parameter for the openUri() method needs to be a string but is currently set as "undefined". Please ensure that the first parameter for mongoose.connect() or mongoose.createConnection() is a valid string. const express = r ...

Enhancing Image Upload with Ajax/JavaScript: Generating Multiple Previews

I've been experimenting with an Ajax image uploader that I found on this website. Currently, I have managed to create duplicate preview images: one displayed under the input field and the other elsewhere on the page labeled as "this what you chose". H ...

The Vue component is only receiving the initial parameter specified in the props

I am encountering a peculiar issue that I cannot seem to understand. Within my Laravel application, I am utilizing Vuejs 3. Specifically, I have developed a component named "MyComponent" which expects two numeric parameters via the use of props. Strangely, ...

Different ways of manipulating images with JavaScript

I attempted to tackle the issue independently, but I'm stumped. Is there a way to adjust the width of an image in JS when the screen dimensions are changed? ...

Create a dynamic Prisma data call by using the syntax: this.prisma['dataType'].count()

I'm currently working on implementing a counting function that can be utilized in all of my objects. In my 'core' file, Prisma is involved in this process. This allows me to execute commands like this.user.count() or this.company.count() I ...

Tips for effectively utilizing Vuelidate to display errors selectively after the user has completed input:

I have implemented a form using Bootstrap-Vue with some Vuelidation code applied to it. <b-form @submit.prevent="onSubmit"> <input type="hidden" name="_token" :value="csrf" /> <transition-group name="fade"> <b-form ...

Issue with remounting in Nextjs 13

import { useRouter, useSearchParams, usePathname } from 'next/navigation'; export function useQueryParams() { const pathname = usePathname(); const router = useRouter(); const searchParams = useSearchParams()!; const updateQu ...

Customizing the formatting of Angular's ui-select2 NoMatches message within a directive

I have a multiple select in a directive template and I want to customize the message that appears when no matches are found. The documentation on suggests overriding the formatNoMatches method for this purpose. This is the select element in my directive& ...

Looking to update a specific element in an array on an hourly basis?

var temperature = [-18 , -18.1 , -18.2, -18.3, -18.4, -18.5, -18.6, -18.7,-18.8, -18.9, -19 , -19.1 , -19.2, -19.3, -19.4, -19.5, -19.6, -19.7,-19.8, -19.9, -20]; $(".warlotemp").html(temperature[0]); $(".warlotemp").append(" C"); I am intere ...

Tips for disabling viewport resizer while accessing the Console panel in Chrome using Control+Shift+J

Currently, I am utilizing the viewport resizer in Chrome to preview how my code appears on various devices. However, I have encountered an issue - whenever I try to access the console using ctrl + shift + j, the viewport resizer opens instead. You can obs ...

Monitoring for incoming chat messages

I'm relatively new to Firebase and Angular2. I'm currently working on creating a chat app that integrates Firebase with Angular2 based on tutorials I've been following. Specifically, I've been using this tutorial to build the chat app ...

What could be causing my array to be undefined upon the creation of a Vue component?

I'm struggling to comprehend why my array is showing as undefined in my Vue component. The issue arises in the following scenario: The SelectCategories.vue component uses the router to navigate to the Quiz.vue component. Here, I utilize props to tran ...

Creating an array of logos in ReactJS with the help of TailwindCSS

After seeing multiple implementations of this feature, I find myself struggling to search for a solution. I can only access the HTML and CSS through inspecting elements, wondering if others are facing the same issue as me. Typically, we aim to implement t ...

magnetic container: stationary container nested within absolutely positioned container

I recently created a page that can be viewed here: [LINK] This page is set up to scroll horizontally, resulting in a row of divs with black borders. However, I am facing an issue with the smaller divs inside (red ones). I want them to stay within the par ...

Utilizing flatMap to implement nested service calls with parameters

Recently, I encountered an issue while working on a service call to retrieve data from a JSON file containing multiple items. After fetching all the items, I needed to make another service call to retrieve the contents of each item. I tried using flatMap f ...