[Vuejs]-Having a button on a child component run a function on the parent

0👍

You need this in your child component:

this.$emit('myEvent')

Then you can do on your parent component:

<my-parent-component v-on:myEvent="doSomething"></my-parent-component>

You can read about firing events at https://v2.vuejs.org/v2/guide/components-custom-events.html . If this is the simple case then using event emiting is fine. But in another cases the better decision is using vuex.

0👍

emit the event and register it in the child component using the "emits" property. Listen to the emitted event at the parent element where you have created the child instance and point the event listener to the function you want to execute.

For Eg.

Parent

<template>
   <child @close="closeIt"></child>
</template>

<script>
   export default {
      methods: {
         closeIt() {
            //DO SOMETHING...
         }
      }
   }
</script>

Child

<template>
   <button @click="closeInParent">Close</button>
</template>

<script>
   export default {
      emits: ["close"],
      methods: {
         closeInParent() {
             this.$emit('close')
         }
      }
   }
</script>

Leave a comment