Vuejs: custom Events

Custom Events: To call a function in Parent Parent.vue from a button in the child Child.vue, we need to use custom events for child to parent communication:

Child.vue

<template>
  <div>
    <div :id="childName"></div>
    <button v-on:click="doStuff()">Do stuff</button>  
  </div>
</template>
<script>
  export default {
    methods: {
      doStuff () {
        this.$emit('childStuff', 'some value from child')
      }
    }
  }
</script>

Parent.vue

<template>
  <div>
    <Child v-on:childStuff="value => { parentStuff(value) }"></Child>
  </div>
</template>
<script>
  import Child from './components/Child';
  export default {
    components: {Child},
    methods: {
      parentStuff (value) {
        alert(value)
      }
    }
  }
</script>

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.