gpt4 book ai didi

javascript - 从 Vue 组件内的 URL 导入 PayPal(或任何其他脚本)

转载 作者:太空宇宙 更新时间:2023-11-03 16:20:56 27 4
gpt4 key购买 nike

我有一个名为 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

最佳答案

这是我使用的组件

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

关于javascript - 从 Vue 组件内的 URL 导入 PayPal(或任何其他脚本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59022554/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com