Using Vue.js: Invoking a Function from a Different Component

Here is the HTML snippet from Component1

 <component2></component2>

This is the <script> block from Component1

export default {
 
  methods: {
    fetchData()
    {
    ...
    }
 }
}

Now, I want to call the method fetchData() in Component2

Here is the <script> block from component2

 export default {
     ...
    }

I have tried using: this.$root.$refs.c1= this; ... this.$root.$refs.c1.fetchData()

I also attempted to set up an event, but unfortunately, nothing seemed to work as expected.

Answer №1

To pass data between Component1 and Component2, you can use the emit method to trigger a fetchData function on Component1:

<component2 @fetch="fetchData()"></component2>

In Component2, make sure to emit the 'fetch' event at an appropriate moment, like during the created lifecycle hook:

export default {
    created() {
        this.$emit('fetch')
    }
}

Answer №2

Make sure the template inside Component2 is as follows:

 <component2 ref="childComp"></component2>

This is how your fetchData method in Component1 should be structured:

export default {
  methods: {
    fetchData() {
      return this.$refs.childComp.fetchData();
    }
  }
}

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

JavaScript code altered link to redirect to previous link

I added a date field to my HTML form. <input type="date" name="match_date" id="matchDate" onchange="filterMatchByDate(event)" min="2021-01-01" max="2021-12-31"> There is also an anchor tag ...

how to switch back and forth between div elements in vue js

I'm currently attempting to toggle between divs, but I'm running into some difficulties. I've realized that I can't include two elements inside the transition directly, and that I need to use a transition-group for this purpose. However ...

Received an error during the module.exports = client process

In my commands folder, I have multiple files that contain slash commands. I am trying to import the client instance from index.js to another file, but when I use module.exports = client;, it ends up executing the entire index.js script unintentionally. I ...

I am trying to access the serial number data from an array of objects in ReactJS. Can anyone guide me

Is there a way to extract data from an array of objects, such as getting the serial number in ReactJS? In my current code snippet, I have an array called "number" with values [1, 2, 3]. My goal is to retrieve and display these numbers as a string like th ...

"The authentication cookie fields are not defined when trying to get the authentication in the Express framework

After setting up my React client on port 3000 and Express on port 5000, I encountered an issue. When logging in, the cookie fields are set without any problems. However, when trying to retrieve the isauth value, it shows as undefined. //login log message ...

Implementing auto-complete functionality for a text box in an MVC application using jQuery

After incorporating code for auto completion in a text box using AJAX results, the following code was utilized: HTML: <div class="form-group col-xs-15"> <input type="text" class="form-control" id="tableOneTextBox" placeholder="Value" > ...

Implementing AJAX to dynamically update information based on user's selection from a dropdown

I need to dynamically adjust the opacity of my graph bars without requiring the user to manually refresh the page. I'm considering using AJAX for this purpose. How can I implement this functionality? const opacitySlider = document.getEle ...

Cross-Origin Resource Sharing (CORS) for enabling the remote inclusion of JavaScript

I have a unique javascript widget that is designed to be embedded from an external server (e.g. ) The javascript, which contains a simple alert('hello'), is generated by a php script. Upon execution, I include a header like this: <?php heade ...

Sinon - the ultimate guide to intercepting the save() function in a mongoose schema

Currently, I am in the process of writing unit tests for an API that utilizes MongoDB in conjunction with mongoose for database access. Within my codebase, there exists a model file that defines and exports a mongoose model as shown below: const { Schema, ...

Tips for utilizing express in your typescript projects

I'm curious about the transition of definition files from tsd to typings, and now to @types. How can I incorporate @types in a node/express project? What is currently preferred and what's the reason for moving from tsd to typing and finally to @t ...

Interacting with a JavaScript button using C# WebBrowser

Can someone please assist me with a problem I'm facing? I have a webpage coded in HTML and Javascript. Whenever I use webBrowser1.Document.GetElementById("hmenu").InvokeMember("click");, the menu pops up on my screen. However, I am unsure how to cli ...

When the bounds are adjusted, removing markers in Vue Cookbook's Google Map

I've encountered an issue with clearing markers after updating new bounds on a map. Whenever I post a request with new bounds, new markers get added to the map while the old ones remain in place. This situation becomes quite awkward for me because the ...

In the test environment, only a portion of the JavaScript code is executed, but it functions properly in both the production and development environments of

Rails 3 Currently facing an issue with a list inside a form: <%= form_for @article do |f| %> <ul> <% @product.each do |p| %> <li id="product_<%=p.id%>"> <div> <%= f.radio_button(:p_id, p ...

What is the method for passing an element object instead of an id in JSXGraph?

I'm attempting to modify var brd2 = JXG.JSXGraph.initBoard('box', {boundingbox: [-8.75, 2.5, 8.75, -2.5]}); to read as var brd2 = JXG.JSXGraph.initBoard(this.$('#box'), {boundingbox: [-8.75, 2.5, 8.75, -2.5]}); Due to the creat ...

What causes the cursor in an editable div to automatically move to the front of the div?

<div className="min-w-[600px] min-h-[36.8px]" > <div id={`editableDiv-${Object.keys(item)}-${index}`} className="p-3" contentEditable suppressContentEditableWarning onInput={(e) => onChange(e)} > ...

Tips for creating an expression within ng-if

I am struggling with placing an expression inside ng-if that needs to be assessed in order for my content to be shown based on its outcome. This is what I currently have: <a ng-if="abc.status===failure" href="http://localhost:3000/abc/abc">image< ...

What is the purpose of creating a new HTTP instance for Socket.io when we already have an existing Express server in place?

As I delve into SocketIO, I've combed through various blogs and documentation on sockets. It seems that in most cases, the standard approach involves creating an HTTP server first and then attaching the socket to it as shown below: var app = express() ...

I need to figure out a way to validate form data dynamically as the number of fields constantly changes. My form data is being sent via Ajax

Click validation is desired. It is requested that before transmitting data, the validate function should be executed. If there is an empty field, a message should be displayed and the data should not be sent to the PHP file. In case there are no empty fi ...

Scrolling with jQuery to create a fixed navigation bar

I'm having an issue with my navbar on my website. I used CSS and jQuery to keep it fixed at the top, but now when I click on a menu item, it doesn't scroll to that section of the page. Can anyone help me troubleshoot this problem? ...

Assign a class to an element depending on its position using JavaScript/jQuery

<ul> <li>Apple</li> <li>Banana</li> <li>Orange</li> </ul> How can I use jQuery to add a class to the second li element in the list without using an existing class or id? ...