Using Vue3 to invoke a method in one component from another component

I'm attempting to call a function from one component to another, specifically from within the setup function. I came across a helpful article on VueMastery which suggests using the following approach:

 methods: {
    reset () {
      this.$refs.counter.reset()
    },
    terminate () {
      this.$refs.counter.terminate()
    }
  }

Unfortunately, I am unable to access these methods within the setup function, nor can I utilize this.$refs. Is there a way to achieve the same functionality within setup or access these methods?

Attempting to access these methods within setup results in them being undefined, and accessing setup data from within these functions or using $refs is also not possible.

While using $refs is a simple way to call functions from another component, I am struggling to find a straightforward method to accomplish this using Vue 3's composition API. Am I overlooking something?

Answer №1

Success! I finally cracked the code. Check out this resource for more details.

Here's the solution:

<script>
 export default {
  setup(props) {
   const counter = ref(null);
   //now I have access to counter.value.reset after it's mounted
   counter.value.reset(); //doesn't work! it's null here
   onMounted(() => {
    counter.value.reset(); //works here
   })
   //don't forget to return counter in return

It seems like there's a straightforward way to handle this in setup, but it comes with a catch:

  • You can't simply call it immediately because setup occurs before mounted. Check out this documentation for more insights.

I'm triggering it based on a specific event - like when someone selects something from a dropdown. By monitoring the v-model, I can easily call it without any issues. Thanks for the help and suggestions. I'm sharing this answer here in case anyone else faces a similar challenge.

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

Partial functionality achieved by integrating Bootstrap for a modal form in Rails

Having an issue with a form in a partial view on Rails 3.2.3 utilizing the bootstrap 2.0.2 modals #myModal.modal .modal-header .close{"data-dismiss" => "modal"}= link_to "x", root_path %h3 Add Tags .modal-body = form_tag '/tagging& ...

The post request fails to send certain variables

I'm experiencing an issue with a form that has rows structured like this: <div class="row unit" onmouseover="this.style.background = '#eeeeee';" onmouseout="this.style.background = 'white';" onclick="if(event.srcElement.nodeNam ...

Utilize service worker in Vue 3 to intercept img src and incorporate an Authorization header

Is there a way to display a private image through Laravel, which is functioning as an API and requires an Authorization header with a Bearer token? I am currently using Quasar, but I don't think that's relevant (unless Quasar offers a solution) ...

The ng-model-options in Angular 2 is set to "updateOn: 'change blur'"

Currently working with angular 2, I am seeking a solution to modify the behavior of ngModel upon Enter key press. In angular 1.X, we utilized ng-model-options="{updateOn: 'change blur'}". How can this be achieved in angular 2? For reference, her ...

Avoid displaying null values in SELECT and GET operations when using node-postgres

Within my Express API functionality, I aim to offer the client flexibility in providing their contact details, namely phone number or website address, with the option of leaving them blank. The SELECT queries in use are as follows: -- Retrieve all users S ...

Scope binding is successful, but accessing the array is only possible after adding an Alert() function

Within my Angular controller, I'm utilizing the SharePoint JavaScript Object Model to fetch data from the Taxonomy (term store). Due to SharePoint's JSOM not being a conventional Angular function that can be easily understood by the scope, I util ...

Is there a way to specifically remove only the last row from a table?

Recently, I encountered a problem with my JS code that adds and removes table rows based on user interaction. Adding rows functioned perfectly, but the issue arose when attempting to delete rows. Instead of deleting only the last row as intended, all rows ...

How do I modify the height of a q-select component in Quasar?

I have been struggling to change the q-select in the quasar framework, despite numerous attempts. <q-select v-model="site1" outline dense class="selection" /> :deep(.selection .q-field__control) {font-size: 13px; width: 250px;} ...

Creating a peaceful web platform with React that supports several user roles

I am in the process of developing a single-page web application that must be completely restful, which is new territory for me. One challenge I'm facing is determining how to efficiently render the user interface for different roles using React. With ...

Ascending with Progress Indicator Slider

After successfully creating a Bootstrap 5 Carousel with an automated count for each slide (limited to 4) and a corresponding progress bar, I encountered an issue with getting the previous button to function correctly. While clicking the next button works s ...

Fix for fixed scrolling in the navigation bar

Having a website that receives traffic from different countries, including Portugal and other non-English speaking places, I decided to add a translation option. However, I encountered an issue with Google's translate feature which displays a banner a ...

Navigating through nested JSON objects in React to display data effectively

I have been struggling for hours to find a solution to this problem with no success. I really need your assistance. The task at hand involves looping through a JSON file and creating a user interface that consists of multiple columns, each containing vari ...

Encountering ERR_EMPTY_RESPONSE when binding ports to a Docker container

Vuejs3 has been successfully installed and npm run dev is running inside a Docker container using the node:latest image. It's a very basic setup. While inside the container, it's definitely starting on http://localhost:5173, as confirmed by curl ...

Attempting to find a solution to successfully transfer an object from the jEditable datatable plugin to my Java Servlet

Currently, I have a Datatable set up and I am utilizing the jeditable plugin to make cells editable and update data. However, after editing a cell and hitting enter, when the data is sent back to my URL Rest endpoint (where I simply have a System.out.print ...

Retrieve the present time of an ongoing CSS3 animation

I've been trying to retrieve the current time of a running animation, but I haven't had any luck so far. I can easily grab the start time using: myelement.addEventListener('webkitAnimationStart', function (evt){ console.log(evt.elaps ...

When a project sets useBuiltIns to 'usage', there is an issue with importing the library generated by Webpack

I am eager to create a versatile UI component library and bundle it with Webpack. However, I encountered an issue when trying to import it into another project that has useBuiltIns: 'usage' specified in the babelrc file. The import fails with the ...

Is there a way to seamlessly update button values in VueJs from an api request without needing to reload the page or manually clicking something? Or perhaps there is an alternative method to achieve this?

I attempted to solve the issue by implementing while(true) within the created method so that it constantly updates by sending frequent requests to Flask. Is there a different approach to updating my value? Vue: let app = Vue.createApp({ data ...

"ModuleNotFound" error occurred when attempting to utilize Netlify lambda functions with external dependencies

https://i.stack.imgur.com/vVmky.jpg I'm currently exploring the capabilities of Netlify, specifically its lambda function feature for running a node function with dependencies. Following a tutorial from CSS-Tricks, my functions/submission-created.js ...

Retrieve the object property based on an array of indices

I am looking to create a function that can retrieve a specific property of an object based on an array of property names const getObjectProperty = (arr: string[], object: any) { // This function should return the desired object property } Expected Outco ...