0

I'm loading the Paypal smart button into a vue component. I've tried loading the external Paypal js script, which appears to create a paypal object.

However when trying to access the paypal object, I get this error:


found in

---> <PaypalButton> at resources/assets/js/components/PaypalButton.vue
       <Root>

After the page is loaded, I can successfully console.log(paypal) in chrome dev tools console window, and I can also successfully create a button in vue to also access it, but it does not appear to be able to referenced in the mounted hook.

Here is the code:

<template>
  <div class="paypal-button-wrapper">
    <div id="paypal-button-container"></div>
    <button @click="showPaypal">Clicking this successfully renders the button</button>
  </div>
</template>

<script>
export default {
  data: () => ({
  }),
  mounted: function () {
    let paypalScript = document.createElement('script');
    paypalScript.setAttribute('src', 'https://www.paypal.com/sdk/js?client-id=AUo4kSgRdH44poEYLQwPdqM24oN8nQc4Jm1HAkWs5vQTAMGu-BBlpfN4xnMDEzSGfj4wjwOy6eLtNKyv&currency=USD');
    document.head.appendChild(paypalScript);
    this.showPaypal(); // fails to render the paypal button, with reference error
  },
  methods: {
    showPaypal: function() {
        paypal.Buttons().render('#paypal-button-container');
    }
  }

};
</script>
greebo3
  • 33
  • 1
  • 5
  • Run `this.showPaypal()` in the appended script's `load` event – Phil Apr 14 '19 at 00:09
  • Possible duplicate of [Call javascript function after script is loaded](https://stackoverflow.com/questions/14644558/call-javascript-function-after-script-is-loaded) – Phil Apr 14 '19 at 00:10
  • @Phil Thanks, pointed me in the right direction. I needed to use paypalScript.onload to solve it. – greebo3 Apr 14 '19 at 20:11

1 Answers1

0

The solution is to use paypalScript.onload. I'm not sure if this is the most direct method, but it does work.

mounted: function () {
    let paypalScript = document.createElement('script');
    paypalScript.setAttribute('src', 'https://www.paypal.com/sdk/js?client-id=SB_ID&currency=USD');
    document.head.appendChild(paypalScript);
    var that = this;
    paypalScript.onload = function () {
        that.showPaypal();
    };
},

Reference: Run the method of the Vue component after the external script is loaded

greebo3
  • 33
  • 1
  • 5