Reputation: 1571
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
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
Reputation: 230
One thing to keep in mind is the flow of passing data from child to parent and vice versa. In a nutshell:
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