JLLMNCHR
JLLMNCHR

Reputation: 1571

Coordinating flow of events in Vue.Js from child A to parent, and from parent to child B

Working with VUE.JS...

Having a 'theParent' component with two childs: 'theForm' and 'theButtons'. (This is a simplification of more complex scenario).

In 'theButtons' exists a 'Clear' button to clean fields of 'theForm' form.

I am able to pass the event from 'theButtons' to 'theParent', but not from 'theParent' to 'theForm' ¿?

Within 'theButtons':

<b-button v-on:click="clean()">Clear</b-button>

methods: {
    clean() {
        this.$emit('clean');
    }
},

Within 'theParent':

<theForm />

<theButtons v-on:clean="clean"/>

methods: {
    clean() {       
        this.$emit('theForm.clean'); //Here is the point I dont know what to put
    }
},

Within 'theForm':

methods: {
    clean() {       
        alert("This is what I want to get executed!!");
    }
},

Upvotes: 1

Views: 279

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Add a ref to the TheForm component then run its method from parent :

<theForm  ref="form" />

<theButtons v-on:clean="clean"/>

methods: {
    clean() {       
        this.$refs.form.clean(); //clean should be a method in theForm component.
    }
},

Or you could add a prop to theForm component which could be updated in parent and watch in child component to clean the form :

<theForm :clean="clean" />

<theButtons v-on:clean="clean"/>

data(){
  return {
     clean:false
  }
},
methods: {
    clean() {       
        this.clean=clean;
    }
},

inside theForm :

props:['clean'],
watch:{
   clean(val){
      if(val){
           this.clean()
       }
   }
}

Upvotes: 1

Helper function
Helper function

Reputation: 230

One thing to keep in mind is the flow of passing data from child to parent and vice versa. In a nutshell:

  1. Parent => Child: if you want to pass data from parent to child, use props.
  2. Child => Parent: if you want to pass data from child to parent, use events.

One solution to your problem is to have <b-button> as a child to the <theForm> as follows:

<theForm v-on:clean="cleanForm">
 <!-- form children -->
 ....
 <theButton />
 ....
</theForm>

Another solution is to have an event bus that passes events between components which is totally unnecessary in your case.

Reference: https://v3.vuejs.org/guide/component-basics.html#passing-data-to-child-components-with-props https://v3.vuejs.org/guide/component-basics.html#listening-to-child-components-events

Upvotes: 1

Related Questions