Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does $emit not work in my vue component

Tags:

vuejs2

I've been banging my head against this problem for hours. I can't see a problem and from what I can tell I am following the documentation here: https://vuejs.org/v2/guide/components-custom-events.html

code below

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="wrap">
  <test-listen>
    <test-emit></test-emit>
  </test-listen>
</div>
<script>
Vue.component('test-listen', {
  data: function(){
    return {};
  },
  methods: {
    customHandler : function(e){
      console.log(e);
      console.log("works");
    }
  },
  template: `
    <div class='test_listen' v-on:custom="customHandler">
      <slot></slot>
    </div>
  `
});

Vue.component('test-emit',{
  data: function(){
    return {};
  },
  methods: {
    clickHandler : function(){
      this.$emit('custom');
    }
  },
  template : `
    <div class='test_emit' v-on:click="clickHandler">
      test
    </div>
  `
});

new Vue({
  el:"#wrap"
});
</script>
<style>
.test_listen{
  display:block;
  padding:20px;
  border:1px solid #000;
}
.test_emit{
  display:block;
  width:100px;
  height:100px;
  background-color:#f0f;
  color:#fff;
  font-weight:700;
  font-size:20px;
}
</style>

But the listeners are definitely bound to the element, because if I dispatch a vanillaJS CustomEvent it triggers the console log just fine. What am I missing?

like image 964
dgeare Avatar asked May 10 '18 17:05

dgeare


1 Answers

I see only one mistake here. You should add v-on to the child component. When you $emit('custom') from inside it will call "customHandler" on the parent component.

Working jsfiddle

    <test-listen>
        <test-emit v-on:custom="customHandler"></test-emit>
    </test-listen>
  
like image 122
Majed Fayazi Avatar answered Oct 02 '22 13:10

Majed Fayazi