1
votes

Let's say I have a component called child. I have data there that I want to access in my parent component. I want to emit an event in the childs mount: this.$emit('get-data', this.data) before finally retrieving it in the parent mount. Is this possible to do / practical? If it is how can one achieve it? If not, what are some better alternatives?

Cheers.

3

3 Answers

2
votes

I am not aware if being able to listen for $emit'd data, from a child mount(), inside a parent mount(). You need to bind the listener to the child component within the parent template. Typical example using 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>
0
votes

An alternative way to pass data from a child to a parent is scoped slots. I think that is more appropriate than events in your case (only pass data without any relation to a real event). But I'm not sure that I fully understood you.

0
votes

I would use the created hook not mounted because you only need access to reactive data and events. You could emit the whole child component and then drill into its data as needed.

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

Check out this fiddle