vue2 call a parent function using $emit from component

Pds Ink picture Pds Ink · Jul 28, 2017 · Viewed 10.3k times · Source

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?

Answer

Muthu Kumaran picture Muthu Kumaran · Jul 28, 2017

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>