【问题标题】:Importing Stripe.js as an ES Module into Vue将 Stripe.js 作为 ES 模块导入 Vue
【发布时间】:2020-06-14 11:56:06
【问题描述】:

I'm trying follow the directions from the stripe elements docs and install the ES module into my Vue payment component.

注意,目前 Stripe 网站 ES 模块安装选项卡已关闭。 Here's a substitute.

我跑了:

npm install @stripe/stripe-js

用法

import {loadStripe} from '@stripe/stripe-js';

const stripe = await loadStripe('pk_test_TYooMQauvdEDq54NiTphI7jx');

当我更改代码以反映模块的安装时,我收到此错误:

30:17 error 解析错误:不能在异步函数外使用关键字“await”

import {loadStripe} from '@stripe/stripe-js';
let stripe = await loadStripe(`pk_test_mypin`)
elements = stripe.elements()
card = undefined;

export default {
    mounted: function () {
        card = elements.create('card', {

        });
        card.mount(this.$refs.card);
    },
    data () {
        return {
            cardHolderName: '',
            stripeErrorMessage: null,
            serverErrorMessage: null,
        }
    },
    computed: {

    },
    methods: {
        processPayment(){

            let self = this;

            stripe.createPaymentMethod(
                'card', card, {
                    billing_details: { name: this.cardHolderName }
            }).then(function(result) {

                if(self.subscribitionCheckout){
                    self.submitPaymentForm(result.paymentMethod);
                } else if (self.changePaymentMethod){
                    self.changePaymentMethod(result.paymentMethod)
                }

                if (result.error) {
                    self.stripeErrorMessage = result.error.message;
                    self.hasCardErrors = true;
                    self.$forceUpdate(); // Forcing the DOM to update so the Stripe Element can update.
                return; 
                }
            });

        },
    },
}

在我有这个之前

let stripe = Stripe(`pk_test_mypin`),
elements = stripe.elements(),
card = undefined;

Also, I based my code on this tutorial

【问题讨论】:

  • 问题不在于导入,而在于您尝试使用它的方式。错误消息会告诉您究竟出了什么问题。
  • @Sirko,删除等待?这给了我另一组 CDN 没有的错误。有什么建议吗?
  • 将其包装在异步函数中并在某处调用该函数。有顶级等待的计划,但 afaik 尚不支持。只需删除 await 就会改变行为。也许在async/await 上阅读一下。
  • 谢谢,我会回来的

标签: javascript vue.js stripe-payments


【解决方案1】:

首先,将预期的顶级vars放入数据中:

stripe: {}, // or whatever data type
elements: {}, // or whatever data type
card: {}, // or whatever data type

其次,创建一个created 生命周期挂钩并在那里加载内容:

created()
{
  loadStripe(`pk_test_TYooMQauvdEDq54NiTphI7jx`).
  then ( (result) =>
  {
    this.elements = result.elements
    // do stuff with card if you have too...

  },
},

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 1970-01-01
    • 2021-10-30
    • 2021-10-13
    • 1970-01-01
    • 2012-11-12
    • 2020-10-21
    • 2021-04-04
    相关资源
    最近更新 更多