从Vue组件内部的URL导入PayPal(或其他脚本)

问题描述 投票:0回答:2

我有一个名为CallToAction的组件,我想导入PayPal,使用其按钮并用脚本激活它,但我不确定如何从Vue组件内的URL正确导入脚本(我不想将其全局在每个页面上,仅将其导入呈现CallToAction组件的页面上。

我尝试了以下操作,但是即使可以在html中看到它,也无法从该脚本访问变量。

<template>
    <div class="paypal-button" id="paypal-plan-container"></div>
</template>

<script>
export default {
    mounted: function() {
        let paypalScript = document.createElement('script')
        paypalScript.setAttribute('src', 'https://www.paypal.com/sdk/js?client-id=sb&vault=true')
        document.head.appendChild(paypalScript)
        paypal.Buttons({
            createSubscription: function(data, actions) {
            return actions.subscription.create({
                'plan_id': 'sb'
            });
            },
            onApprove: function(data, actions) {
            alert(data.subscriptionID);
            }
        }).render('#paypal-plan-container');
    }
}
</script>

给出此错误ReferenceError: paypal is not defined

javascript vue.js paypal
2个回答
1
投票

这里是我使用的组件

<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
投票

当脚本期望直接包含在页面中时,可能值得寻找一个vue包装器来解决通过vue组件加载该脚本的问题。您需要this吗?

© www.soinside.com 2019 - 2024. All rights reserved.