我正在将Paypal智能按钮加载到vue组件中。我尝试加载外部Paypal js脚本,该脚本似乎创建了一个paypal对象。
但是,当尝试访问贝宝对象时,出现此错误:
found in
---> <PaypalButton> at resources/assets/js/components/PaypalButton.vue
<Root>
加载页面后,我可以在chrome dev工具控制台窗口中成功console.log(paypal),也可以在vue中成功创建一个按钮来访问它,但是它似乎无法被引用在已安装的挂钩中。
代码如下:
<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¤cy=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>
答案 0 :(得分:0)
解决方案是使用paypalScript.onload。我不确定这是否是最直接的方法,但是它确实有效。
mounted: function () {
let paypalScript = document.createElement('script');
paypalScript.setAttribute('src', 'https://www.paypal.com/sdk/js?client-id=SB_ID¤cy=USD');
document.head.appendChild(paypalScript);
var that = this;
paypalScript.onload = function () {
that.showPaypal();
};
},
参考:Run the method of the Vue component after the external script is loaded