0

for some reason emited event doesn't handles by parent component

HTML:

<template id="parent-template">
  <div>
    <h1>Parent: {{message}}</h1>
    <child-component message="Child message"></child-component>
  </div> 
</template>    
<template id="child-template">
  <div>
    <h2>Child: {{message}}</h2>
    <button v-on:click="changeMessage('Changed')">Change</button>
  </div> 
</template>

<div id="app"> 
  <parent-component message="Parent message"></parent-component>
</div>

JS (es5):

Child:

Vue.component("child-component", {
  template: "#child-template",
  props:['message'],
  methods:{
    changeMessage: function(newMessage){
      this.message = newMessage;
      this.$emit("message-changed", newMessage); 
    }
  }
});

Parent:

Vue.component("parent-component", {
  template: "#parent-template",
  props:['message'],
  mounted: function(){
    var v = this;
    this.on("message-changed", function(newValue){
      alert("Emit handled!");
      v.message = newValue;
    });
  }
});

So, everythings looks fine, but nothing happens when event fires. Why?

Yes Man
  • 321
  • 1
  • 5
  • 14

1 Answers1

0

You cannot check for the emitted event on a mounted function, since the child Vue instances are not instantiated at that point. If you want to run the code AFTER everything has been rendered which is what I am assuming you are after then you need to run the code after a tick.

this.$nextTick(function () { // Your code goes here }

Also, for clarity, I would normally do a v-on:message-changed="parentMethod()" inside of the HTML. That way the parent is not tightly coupled to the child component at the mounted.

<child-component v-on:message-changed="parentMethod()"> </child-component>

Below is the Vue Documentation regarding the mounted information I provided: https://v2.vuejs.org/v2/api/#mounted

tony19
  • 125,647
  • 18
  • 229
  • 307
Scornwell
  • 597
  • 4
  • 19