You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中如何显示PayPal按钮?代码构建成功但按钮不显示

解决Vue.js中PayPal按钮不显示且报paypal is not defined的问题

你的核心问题是PayPal脚本的加载顺序不对,导致Vue组件执行逻辑时paypal对象还没被初始化,所以抛出了ReferenceError。下面给你两种可靠的解决方案:

方案一:全局引入PayPal脚本(最简单)

在Vue项目的入口HTML文件(比如public/index.html)中,直接添加PayPal的脚本引用,让页面在加载时就先加载好PayPal的资源:

<!-- 在index.html的<head>或<body>末尾添加 -->
<script src="https://www.paypalobjects.com/api/checkout.js"></script>

然后你的组件代码可以保持不变,因为当组件的mounted钩子执行时,paypal对象已经全局可用了。

方案二:组件内动态加载脚本(更灵活)

如果不想全局引入脚本,可以在组件的mounted钩子中动态创建并加载脚本,确保脚本加载完成后再渲染PayPal按钮:

<template>
<div id="container">
  <input type="text" class="form-control">
  <div id="paypal-button"></div>
</div>
</template>

<script>
export default {
  mounted() {
    // 创建脚本元素
    const paypalScript = document.createElement('script');
    paypalScript.src = 'https://www.paypalobjects.com/api/checkout.js';
    
    // 脚本加载完成后执行渲染逻辑
    paypalScript.onload = () => {
      paypal.Button.render({
        env: 'sandbox',
        client: {
          sandbox: 'ARQ-WKAkFn3g4C111Ud3lLaUAfzagvJ_pmkLKBVMASvv6nyjX3fv3j0gtBdJEDhRPznYP9sLtf9oiJfH',
          production: 'EFNo9sAyqiOmnlRHsAdXiGBf6ULysEIfKUVsn58Pq6ilfGHVFn03iVvbWtfiht-irdJD_df1MECvmBC2'
        },
        locale: 'en_US',
        style: {
          size: 'medium',
          color: 'gold',
          shape: 'pill',
        },
        commit: true,
        payment: function(data, actions) {
          return actions.payment.create({
            transactions: [{
              amount: {
                total: '11',
                currency: 'USD'
              }
            }]
          });
        },
        onAuthorize: function(data, actions) {
          return actions.payment.execute().then(function() {
            window.alert('Thank you for your purchase!');
          });
        }
      }, '#paypal-button');
      console.log('notification mounted');
    };
    
    // 将脚本添加到页面
    document.body.appendChild(paypalScript);
  }
}
</script>

额外提示

  • 确保你的#paypal-button元素在mounted钩子执行时已经存在(你的模板里已经正确定义了,这一点没问题)
  • 现在PayPal官方推荐使用最新的JS SDK(替换旧的checkout.js),新SDK的集成方式更适配现代前端框架,如果你有时间可以考虑升级哦。

内容的提问来源于stack exchange,提问作者charles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:44:05