Trigger a child-mounted event and retrieve it from the parent component

Imagine I have a component named child. There is some data stored there that I need to retrieve in the parent component. To accomplish this, I plan to emit an event in the childs mount using

this.$emit('get-data', this.data)
, and then receive it in the parent mount. Is it actually achievable and practical? If so, how can one go about implementing it? If not, what are some superior alternatives?

Cheers.

Answer №1

It's uncertain whether you can listen for emitted data from a child component's mount() function inside the parent component's mount(). To achieve this, you need to bind the listener to the child component within the parent template. Here is a common example using Single File Components (SFC):

Child.vue:

export default{
   name: 'child',
   mount(){
     this.$emit('get-data', this.data);
   }
}

Parent.vue:

<template>
   <div>
      <child v-on:get-data="doSomething"></child>
   </div>
</template>
<script>
import Child from './Child';
export default{
   name: 'parent',
   components: { Child },
   methods(){
     doSomething(data){
       //Do something with data.
     }
   }
}
</script>

Answer №2

One interesting method for sending information from a child component to its parent is through the use of scoped slots. This approach might be more suitable in scenarios where data needs to be passed without any direct correlation to an event. However, I'm uncertain if I have grasped your situation completely.

Answer №3

For optimal performance, I recommend utilizing the created hook instead of mounted, as you only require access to reactive data and events. You can emit the entire child component and then navigate through its data as necessary.

template

<child-component @emit-event="handleEvent">
  {{ parentData }}
</child-component>

child

Vue.component('child-component', {
  template: '<div><slot/></div>',
  data() {
    return {
      childData: 'childData', 
    }
  },
  created() {
    this.$emit('emit-event', this)
  }
})

parent

new Vue({
  el: "#app",
  data: {
    parentData: undefined,
  },
  methods: {
    handleEvent({ childData }) {
      this.parentData = childData
    }
  }
})

Feel free to explore this demonstration

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

What is the best method to retrieve the value of a button that has been selected from a collection of buttons?

Within a functional component, there is an issue where the choose function keeps printing 'undefined'. I have utilized const [chosen, setchosen] = useState([]) within this code snippet. The full code has been correctly imported and the purpose of ...

How can a JSON string be assigned to a variable for use in a Google pie chart?

I am currently experiencing an issue with my web server. I am sending a JSON object as an argument via render_template to my website, where I intend to use this data to display a Google pie chart. The problem arises when I try to assign the Google pie cha ...

Why is the Zip archive downloader not functioning properly when using Node.js and Archiver (Unexpected end of archive error)?

Looking to download multiple files using archiver with express. The server should respond to a post request from the client by sending a .zip file. However, there seems to be an issue where WinRAR displays an error message "! 98I9ZOCR.zip:Unexpected end of ...

New approach: AngularJS - Using nested ng-click events

Looking for a solution to a problem with my html code: <div class="outerdiv" data-ng-click="resetText()"> <div class="innerdiv" data-ng-click="showText()"> {{ text }} </div> </div> The outer div has an ng-click fun ...

"Aligning the title of a table at the center using React material

I have integrated material-table into my react project and am facing an issue with centering the table title. Here is a live example on codesandbox: https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js I specifically want to center the title "A ...

The tooltip in nvd3 is displaying the index instead of the label

I'm encountering an NVD3 tooltip issue with my multichart (multiline chart). The XAxis labels are set as JAN, FEB, MAR... DEC. However, when I hover over the graph, it displays 0, 1, 2, 3... 11 as the tooltip title instead of the month names. Here is ...

Interactively retrieving objects from a JavaScript array based on their keys

let arr = [{id:'one',val:1},{id:'two',val:2}] for( let ii of arr ) { if( ii.hasOwnProperty('id') ) arr[ii.id] = ii } This code snippet allows for accessing the elements in the array by their 'id' key. For exampl ...

Dealing with multiple submit buttons in a form with Angular JS: best practices

I'm using AngularJS and I have a form where the user can enter data. At the end of the form I want to have two buttons, one to "save" which will save and go to another page, and another button labeled "save and add another" which will save the form an ...

Combining the powers of Nextjs and Vue

Currently utilizing Vue.js, I am now looking to leverage the Next.js framework for its SEO capabilities, server-side rendering features, and other advantages. While I do have some experience with React, my primary focus is on mastering Vue.js. Is it poss ...

Cease / Cancel Ajax request without activating an error signal

I am looking for a way to intercept all ajax requests on a page and stop/abort some of the requests based on certain criteria. Although initially using jqXHR.abort(); worked, it caused the error event of all the aborted requests to be triggered, which is n ...

Generating a random number to be input into the angular 2 form group index can be done by following these

One interesting feature of my form is the dynamic input field where users can easily add more fields by simply clicking on a button. These input fields are then linked to the template using ngFor, as shown below: *ngFor="let data of getTasks(myFormdata); ...

Difficulty in jQuery's clone() function: cloning an input element without its value

I have successfully implemented jquery's .clone() method, but I'm facing an issue where the value of the previous input field is also getting cloned along with it. How can I prevent this from happening? Below is my code snippet: function addrow ...

Ways to append a number to the start or end of an array using JavaScript

Can you help me figure out why the function to order the "s" array from minor to major is adding the number at the end instead of the beginning? The if statement seems to be true (2 < 7 = true) but the logic is not working as expected. Any advice on how to ...

Step-by-step guide on clipping a path from an image and adjusting the brightness of the remaining unclipped area

Struggling to use clip-path to create a QR code scanner effect on an image. I've tried multiple approaches but can't seem to get it right. Here's what I'm aiming for: https://i.stack.imgur.com/UFcLQ.png I want to clip a square shape f ...

Nodejs application crashes due to buffer creation issues

router.post('/image', multipartMiddleware , function(req, res) { var file_name = req.body.name; var data = req.body.data; var stream = fs.createReadStream(data); //issue arises here return s3fsImpl.writeFile(file_name , stream).t ...

Adding items to a JSON document

My task involves creating a pseudo cart page where clicking on checkout triggers a request to a JSON file named "ordersTest.json" with the structure: { "orders": [] }. The goal is to add the data from the post request into the orders array within the JSO ...

How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval(). Here's the snippet of my code: export class SmileyDirective { FillGraphValues() { console.log("The FillGraphValues function works as expect ...

Unable to handle JQuery POST to PHP in success function

I am struggling with a jQuery post function that is supposed to call a PHP script in order to retrieve a value from the database. Although I can see in Firebug that the PHP file is being called and returning a 200 OK status, the success function in my JS ...

Tips for repairing damaged HTML in React employ are:- Identify the issues

I've encountered a situation where I have HTML stored as a string. After subsetting the code, I end up with something like this: <div>loremlalal..<p>dsdM</p> - that's all How can I efficiently parse this HTML to get the correct ...

The attempt to cast to a number for the value of "[object Object]" at the specified path failed in mongoose

My schema is structured like this: module.exports = mongoose.model('Buyer',{ username: String, password: String, email: String, url: String, id: String, firstName: String, lastName: String, credit: Number, }); Wh ...