i'm trying to call a parent methods from child component, but it seems not working.. here the code:
index.html
<div class="percorso"v-on:removeall="pathlengthTozero()">
</div>
component
Vue.component('lista-percorso', {
template:`
<div class="col-lg-2 col-xs-2">
<div class="removeall pull-right" v-on:click="removeall()"></div>
</div>`,
methods:{
removeall : function(){
this.listaSelezionati = [];
this.$emit('removeall');
}
}
parent method
pathlengthTozero : function(){
il_tuo_percorso = [''];
}
seems that "pathlengthTozero" is not called on emit which is the correct way to use it?
Many Vue patterns involve passing data from a parent component to its children using props. But what if we need a child to affect its parent? Using emit, we can trigger events and pass data up the component heirarchy. This is useful for things like: How does Vue Emit Work? When we emit an event, we invoke a method with one or more arguments:
We need to take care of these steps to emit events in Vue: Think about the trigger for the event: a condition in a method, computed property or watcher in child component from where the event is emitted Emit the event with this.$emit ("my-custom-event", \ [data\]) when the condition is met
This gives it way more power than just a method inside the child component. When using the $emit method, as seen above, the first argument is the name of the event and the rest are argument passed to the method. So you can something as below as well:
Catch the event in a parent component Now, inside the parent component we need to catch the emitted event and setup a handler method there. Inside our handleFormData method we are simply putting the form data passed from the child component in the local state of the parent component.
You need to put this v-on:removeall="pathlengthTozero"
to the component <lista-percorso>
like below,
<lista-percorso v-on:removeall="pathlengthTozero"></lista-percorso>
and this.$emit
will able to fire the parent method.
Sample Demo:
Vue.component('lista-percorso', {
template:`
<div class="col-lg-2 col-xs-2">
<div class="removeall pull-right" v-on:click="removeall()">xxxxxxxxxx</div>
</div>`,
methods:{
removeall : function(){
this.listaSelezionati = [];
this.$emit('removeall');
}
}
})
var App = new Vue({
el: '#app',
methods:{
pathlengthTozero : function(){
alert('hello');
il_tuo_percorso = [''];
}
}
});
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div class="percorso" ></div>
<lista-percorso v-on:removeall="pathlengthTozero"></lista-percorso>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With