user762579
user762579

Reputation:

Vue.js 2 How to capture events fired by child comonent?

In a Payments.vue component , I would like to capture the events fired by a child component PayPalCheckout.vue

PayPalCheckout.vue ( child )

methods: {
    ...
     onAuthorize(data, actions) {
      const vue = this;
      vue.$emit('paypal-paymentAuthorized', data);
      return actions.payment.execute().then((response) => {
        vue.$emit('paypal-paymentCompleted', response);
      });
    },
    onCancel(data) {
      const vue = this;
      vue.$emit('paypal-paymentCancelled', data);
    },
  },
  ...
 }

Payments.vue . ( Parent component )

 export default {
   events: {
     'paypal-paymentAuthorized': function (data) {
       console.log('paypal-paymentAuthorized fired: ', data)
     },
     'paypal-paymentCompleted': function (data) {
       console.log('paypal-paymentCompleted fired: ', data)
     },
     'paypal-paymentCancelled': function (data) {
       console.log('paypal-paymentCancelled fired: ', data)
     }
   },
   ...

But I don't get anything in the console.log... why ?

Upvotes: 0

Views: 280

Answers (2)

user320487
user320487

Reputation:

The child component can emit to the parent component via the $parent property:

// PayPalCheckout.vue
onAuthorize(data, actions) {
  this.$parent.$emit('paypal-paymentAuthorized', data);
  return actions.payment.execute().then((response) => {
    this.$parent.$emit('paypal-paymentCompleted', response);
  });
},
onCancel(data) {
  this.$parent.$emit('paypal-paymentCancelled', data);
},

The parent can explicitly listen for those events:

// Payments.vue
export default {
  created () {
    this.$on('paypal-paymentAuthorized', data => {
      console.log('paypal-paymentAuthorized fired: ', data)
    })
    this.$on('paypal-paymentCompleted', data => {
      console.log('paypal-paymentCompleted fired: ', data)
    })
    this.$on('paypal-paymentCancelled', data => {
      console.log('paypal-paymentCancelled fired: ', data)
    })
  }
}

Upvotes: 0

jostrander
jostrander

Reputation: 754

You need to specifically capture the events in the parent like this:

<child-component @paymentaccepted="someMethodOnParent"></child-component>

Then in the child you can emit:

methods: {
  onAuthorize(data) {
    this.$emit('paymentaccepted', data)
  }
}

Upvotes: 1

Related Questions