[Vuejs]-Define a parent method

0👍

There are different ways to handle this.

Method 1: $emit an event

The typical data flow structure in Vue.js is parents pass props down, and children emit events up.

In your case your parent is the modal and it has no props to pass so all you need to worry about is emitting a event from your child contact-form and listening for that event on the parent.

In your modal you have the methods submit and cancel so you could define your template like this.

<template>
    <contact-form @submit="submit" @cancel="cancel"/>
</template>

Then in your contact form component something like

<template>
  <div id="the-form">  
    <input type="text" v-model="formData.name">
    <input type="text" v-model="formData.email">.
 
    <button @submit="submitData">Submit</button>
    <button @canel="cancel">Cancel</button>
  </div>
</template>

<script>    
   ...
    data(){
        return {
           formData: {}
         }
    },
    methods:{
      submitData(){
           this.$emit('submit',this.formData);
      },
      cancel(){
         this.$emit('cancel');
      }

    }

In your modal components methods you simply get the values that are passed from the @submit and then do what ever you need with them.

methods:{
   submit(data){
       console.log(data); //do something with the emitted data
   }
}

Note that you can also often simply emit directly from the button @click definition without adding extra methods as long as you don’t need to process the data or something of the sort.

<button  @click="$emit('submit',formData)">Submit</button>
<button @click="$emit('cancel)">Cancel</button>

Method 2: Use the $parent "reference"

In this basic case you could simply reference your parent in your child and save a lot of work.

In your contact-form methods just reference your parent’s submit() and cancel() methods.

 methods:{
  submitData(){
       this.$parent.submit(this.formData);
  },
  cancel(){
     this.$parent.cancel();
  }

}

Or even more simply, as above with buttons, just do…

<button  @click="$parent('submit',formData)">Submit</button>
<button @click="$parent('cancel)">Cancel</button>

Edit

After further discussion you indicated to want to reverse this having the child tell the parent what to do.

In that case you can still use something like the second method. You can add a ref to your child component and then ref that child’s methods through that ref.

So whenever you put a child in your modal you would do something like this.

 <the-child-component ref="modalContent"></the-child-component>

Then in your modal you would reference your child methods like this.

submit(){
    this.$refs.modalContent.submit();
},

See a working example here > https://jsfiddle.net/skribe/3bwpafr1/

Leave a comment