【问题标题】:vue2 call a parent function using $emit from componentvue2 使用组件中的 $emit 调用父函数
【发布时间】:2018-01-04 09:38:46
【问题描述】:

我正在尝试从子组件调用父方法,但它似乎不起作用..这里的代码:

index.html

<div class="percorso"v-on:removeall="pathlengthTozero()">
</div>

组件

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');
    }
}

父方法

    pathlengthTozero : function(){
       il_tuo_percorso = [''];
    }

似乎没有在发射时调用“pathlengthTozero”,这是使用它的正确方法吗?

【问题讨论】:

  • 你可以使用 v-on 来监听 DOM 事件。 v-on:removeall 没有任何意义。
  • 你在哪里使用了这个lista-percorso组件?

标签: methods vuejs2 emit


【解决方案1】:

你需要把这个v-on:removeall="pathlengthTozero" 放到组件&lt;lista-percorso&gt; 中,如下所示,

<lista-percorso v-on:removeall="pathlengthTozero"></lista-percorso>

this.$emit 将能够触发父方法。

示例演示:

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>

【讨论】:

    【解决方案2】:

    您应该将事件侦听器放在使用它的子组件上

    <div class="percorso">
        <lista-percorso v-on:removeall="pathlengthTozero"></lista-percorso>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 2016-06-26
      • 1970-01-01
      • 2017-06-13
      • 2022-11-04
      相关资源
      最近更新 更多