Kyaw Zay Win
Kyaw Zay Win

Reputation: 11

Vue emit (did not listen the emitting event from the child)

I am a beginner and I tried vue emit event. But the event do not listen from the parent. Please Help Me!!

In App.vue

<app-header v-bind:somethings='name' @custom-event-name="setName"></app-header> 

setName(childName){
 this.name= childName;

}

In Body.vue

<button @click="changeName"> click me to change name </button>

changeName: function(){
        this.$emit('custom-event-name', 'Some Value');    }

Upvotes: 1

Views: 350

Answers (1)

Montgomery Watts
Montgomery Watts

Reputation: 4034

From what I'm seeing in your script section, you're not importing the Body component, which is where you are trying to emit an event.

Right now you have this:

<script>
import Header from './components/Header.vue';
export default {
  components:{
    'app-header': Header,
    'app-body' : Body
  },
  data () { 
    return  {
      name: 'John', 
    } 
  }, 
  methods: {
    setName(payload) {
      this.name = payload;
    }
  }
}
</script>

There isn't an import statement for the Body component, so your parent component doesn't know what Body is. To fix this you just need to add an import like you've done for Header. It might look like this: import Body from './components/Body.vue';

Now that the Body component is being used, you need to include it in your template. You'll do the same thing you did for app-header, and include a tag like this <app-body></app-body>. Finally, you need to add the event listener so the parent knows when to run setName. This gets added to the app-body tag, and will end up looking like this: <app-body @custom-event-name="setName"></app-body>

Upvotes: 1

Related Questions