简体   繁体   中英

Emit an event from child mount and access from parent mount

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.

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>

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM