[Vuejs]-Passing functions as props to child components

4๐Ÿ‘

โœ…

You should $emit an event (name, say, yes) at the modal:

<button @click="$emit('yes')" data-modal-button-ok>Yes</button>

Or, use a method:

<button @click="handleYesClick" data-modal-button-ok>Yes</button>
methods: {
  handleYesClick() {
    this.$emit('yes');
  }
}

And listen to it in the parent using:

<modal ... v-on:yes="someCodeToExecute"></modal>

or (shorthand):

<modal ... @yes="someCodeToExecute"></modal>

Demo:

Vue.component('modal',  {
  template: "#modal",
  name: 'modal',
  props: ['id', 'title', 'body']
})
new Vue({
  el: '#app',
  data: {},
  methods: {
    methodAtParentYes() {
      alert('methodAtParentYes!');
    },
    methodAtParentCancel() {
      alert('methodAtParentCancel!');
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<template id="modal">
    <div>
        <div :id="`${id}`" data-modal>
           <div data-modal-title>
               {{title}}
           </div>
           <div data-modal-body>
               {{body}}
           </div>
           <div data-modal-footer>
               <button @click="$emit('yes')" data-modal-button-ok>Yes</button>
               <button @click="$emit('cancel')" data-modal-button-cancel>Cancel</button>
           </div>
       </div>
   </div>
</template>

<div id="app">
  <modal id="1" title="My Title" body="Body" @yes="methodAtParentYes" @cancel="methodAtParentCancel"></modal>
</div>
๐Ÿ‘คacdcjunior

4๐Ÿ‘

There are two ways to do this.


The first way is you could pass the method down as a prop, just like you would pass anything else and then in the Modal component just call that prop right in the click handler.

Parent.vue

<template>
   <Modal id="x" title="y" body="x" :handleYes="handleYes"></Modal>
</template>
<script>
  methods: {
    handleYes () {
      // do something
    }
  }
</script>

Modal.vue

<button @click="handleYes()">Yes</button>

The other way is to use $emit. So in Modal.vue you would define a method to emit an event and then listen for that event in the parent and do call the method there.

Modal.vue

<template>
  <button @click="emitEvent">Yes</button> 
</template>
<script>
  methods: {
    emitEvent () {
      this.$emit('userClickedYes')
    }
  }
</script>

Parent.vue

<template>
   <Modal id="x" title="y" body="x" @userClickedYes="handleYes"></Modal>
</template>
<script>
  methods: {
    handleYes () {
      // do something
    }
  }
</script>
๐Ÿ‘คcodyj

Leave a comment