vue2 call a parent function using $emit from component
Asked Answered
H

2

5

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?

Halfmoon answered 28/7, 2017 at 10:44 Comment(2)
You can use v-on to listen to DOM events. v-on:removeall doesn't make any sense.Threecolor
Where did you use this lista-percorso component?Pebbly
C
11

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>
Crossruff answered 28/7, 2017 at 10:59 Comment(0)
P
0

you should put the event listener on the child conponent where it is used

<div class="percorso">
    <lista-percorso v-on:removeall="pathlengthTozero"></lista-percorso>
</div>
Pebbly answered 28/7, 2017 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.