n How to pass data from child to parent component with custom events in Vuejs | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

You can send data from a child to a parent component by means of Vue’s built-in $emit() method. The first parameter of $emit is the event that should be listened for in the parent component. The second (optional) parameter is the data value to pass.

Example Parent Component:


<template>
  <div>
    <Child v-on:childToParent="onChildClick" v-on:increment="counter++"></PassProps>
  </div>
</template>
<script>
import Child from '@/components/Child.vue'
export default {
  data () {
    return {
      counter: 0,
      fromChild: '',
    }
  },
  components: {
    Child
  },
  methods: {
    onChildClick (value) {
      this.fromChild = value
    }
  }
}
</script>

 

In this example, the parent listens for the childToParent event (defined by the $emit method) and triggers the onChildClick() method when the event is received. This method in turn sets the fromChild variable. It also emits an increment event in a simpler way when the button is clicked, by placing $emit inline in the template.

Example Child Component:

 


<template>
  <div class="child">
    <button type="button" name="button" v-on:click="$emit('increment')">Click me to increment!</button>
    <label for="child-input">Child input: </label>
    <input id="child-input" type="text" name="msg" v-model="childMessage" v-on:keyup="emitToParent">
  </div>
</template>
<script>
export default {
  data() {
    return {
      childMessage: ''
    }
  },
  name: 'Child',
  methods: {
    emitToParent (event) {
      this.$emit('childToParent', this.childMessage)
    }
  }
}
</script>

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook