[Vuejs]-Importing PayPal (or any other script) from URL inside component in Vue

3👍

Here is the component I used

<template>
  <div ref="paypal"></div>
</template>

<script>
export default {
  data() {
    return {
      order: {
        description: "Buy thing",
        amount: {
          currency_code: "USD",
          value: 1000
        }
      }
    };
  },
  mounted: function() {
    const script = document.createElement("script");
    const ClientID = "";
    script.src = `https://www.paypal.com/sdk/js?client-id=${ClientID}`;
    script.addEventListener("load", this.setLoaded);
    document.body.appendChild(script);
  },
  methods: {
    setLoaded: function() {
      window.paypal
        .Buttons({
          createOrder: (data, actions) => {
            return actions.order.create({
              purchase_units: [this.order]
            });
          },
          onApprove: async (data, actions) => {
            const order = await actions.order.capture();
            // ajax request
          },
          onError: err => {
            console.log(err);
          }
        })
        .render(this.$refs.paypal);
    }
  }
};
</script>

0👍

When a script expects to be included directly in the page, it’s probably worth looking for a vue wrapper to take care of the issue of loading it via a vue component. Is this what you need?

Leave a comment