[英]How to use external JavaScript objects in Vue.js methods
我正在尝试让 Stripe 与我的 Vue.js 2 应用程序一起工作。 出于 PCI-DSS 的原因,Stripe 要求他们的 Javascript总是从js.stripe.com
加载。 我已按照以下说明操作:
但是当我尝试使用该库时,出现'Stripe' is not defined
错误。 这些解决方案的目的似乎只是将<script>
标签添加到输出 HTML(例如用于分析)中,而不是实际使用该脚本中的函数和对象。
这是我的组件 Javascript 的样子:
<script>
export default {
name: "PaymentPage",
mounted() {
let stripeScript = document.createElement('script');
stripeScript.setAttribute('src', 'https://js.stripe.com/v3/');
document.head.appendChild(stripeScript);
let s = Stripe('pk_test_Fooo');
console.log(s);
}
}
</script>
我也尝试将脚本标记添加到我的public/index.html
文件中,但我得到了相同的结果。 这可能是我的首选路线,因为 Stripe 鼓励开发人员在网站的所有页面上导入他们的脚本。
<!DOCTYPE html>
<html lang="en">
<head>
// ...
<script src="https://js.stripe.com/v3/"></script>
</head>
如何从外部 CDN 中提取脚本并在组件的 Javascript 中使用它?
我知道有一些库可以将 Vue.js 与 Stripe 集成(例如matfish2/vue-stripe和jofftiquez/vue-stripe-checkout ),但前者不能正确导入(我遇到了问题 #24 )后者是针对旧的 Stripe API 构建的,新版本仍处于测试阶段。
在检查Stripe
是否存在之前,您没有给脚本加载时间。 你需要的是这样的:
<script>
export default {
name: "PaymentPage",
mounted() {
let stripeScript = document.createElement('script');
stripeScript.setAttribute('src', 'https://js.stripe.com/v3/');
stripeScript.onload = () => {
let s = Stripe('pk_test_Fooo');
console.log(s);
};
document.head.appendChild(stripeScript);
}
}
</script>
感谢yuriy636 的评论,我意识到错误仅来自 linter,大概无法静态地弄清楚我在做什么。
我选择将脚本放入index.html
,然后确保我用以下方法压缩了 linter 错误:
// eslint-disable-next-line no-undef
let s = Stripe('pk_test_Fooo');
就我而言,我仍然在调用特定脚本的函数时出错。 因此需要指定“窗口”范围。 此外,如果您需要访问“onload”函数内的任何 Vue 元素,则需要为“this”实例添加一个新变量。
<script>
export default {
name: "PaymentPage",
mounted() {
let stripeScript = document.createElement('script');
// new variable for Vue elements.
let self = this;
stripeScript.onload = () => {
// call a script function using 'window' scope.
window.Stripe('pk_test_Fooo');
// call other Vue elements
self.otherVueMethod();
};
stripeScript.setAttribute('src', 'https://js.stripe.com/v3/');
document.head.appendChild(stripeScript);
}
}
我在 Vue 2.6 上使用过这个。
只需安装 npm 包npm install @stripe/stripe-js
并像常规导入一样使用它
import { loadStripe } from "@stripe/stripe-js";
export default {
async mounted() {
// init stripe
const stripe = await loadStripe('your_stripe_key_here');
this.stripe = stripe; // store the stripe instance
// access the stripe instance in your methods or where you want to use them
},
}
它的工作时间为 2022 年 1 月 6 日。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.