[英]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.