简体   繁体   中英

Vue - Passing data from child to parent - Basic emit not working

I have a basic Vue2 component and I am trying to pass data from the child to the parent component using $emit . Note, my-component contains a table where when I click on a row, onRowClick fires successfully, outputting 'foobar' to the console. For some reason, I'm not able to get the parent method to fire on $emit and success isn't being logged to console. Any idea why this is?

import Vue from 'vue';
import MyComponent from "./components/MyComponent.vue";

window.onload = function () {
   var main = new Vue({
      el: '#app-v2',
      components: { MyComponent },
      methods: {
         onCouponApplied(data) {
            console.log("Success, coupon applied, " + data);
            this.saying = "Sunglasses are " + data; //Sunglasses are cool
         }
      },
      data: {
         contactEditPage: {
            saying: ""
         }
      }
   });
}

MyComponent.vue

export default {
        methods: {
            onRowClick(event){ 
               this.$emit('applied', 'Cool');
               console.log("foobar");
            }

HTML

<div id="app-v2">
    <my-component @applied="onCouponApplied"></my-component>
     {{ saying }} //trying to output: sunglasses are cool
</div>

I faced the same problem. I fixed this issue by using $root.

For example in parent Vue component

mounted(){
    this.$root.$on('event-name',function(value){
        // code
    });
},

And child component should be like this:

this.$root.$emit('event-name',[data]);

Hope can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM