[英]How to use an external non vue script in vue
我嘗試使用不是基於 vue 的外部腳本( https://libs.crefopay.de/3.0/secure-fields.js )
我通過 -tags 將腳本添加到 index.html
但是當我嘗試對一個對象進行分解時,就像在腳本發布者的例子中一樣。
let secureFieldsClientInstance =
new SecureFieldsClient('xxxxx',
this.custNo,
this.paymentRegisteredCallback,
this.initializationCompleteCallback,
configuration)
Vue 說“未定義‘SecureFieldsClient’”
如果我用這個。
let secureFieldsClientInstance =
new this.SecureFieldsClient('xxxxx',
this.custNo,
this.paymentRegisteredCallback,
this.initializationCompleteCallback,
configuration)
secureFieldsClientInstance.registerPayment()
Vue 說:v-on 處理程序中的錯誤:“TypeError:this.SecureFieldsClient 不是構造函數”
我的代碼:
methods: {
startPayment () {
this.state = null
if (!this.selected) {
this.state = false
this.msg = 'Bitte Zahlungsweise auswählen.'
} else {
localStorage.payment = this.selected
let configuration = {
url: 'https://sandbox.crefopay.de/secureFields/',
placeholders: {
}
}
let secureFieldsClientInstance =
new SecureFieldsClient('xxxxx',
this.custNo,
this.paymentRegisteredCallback,
this.initializationCompleteCallback,
configuration)
secureFieldsClientInstance.registerPayment()
// this.$router.replace({ name: 'payment' })
}
}
}
我的錯誤在哪里?
編輯:更新了洞問題
這是您提供的上下文的最小 Vue 應用程序,它有效: https : //codepen.io/krukid/pen/voxqPj
如果沒有其他詳細信息,很難說出您的具體問題是什么,但很可能在您的方法執行后加載了庫,因此window.SecureFieldsClient
預計尚未定義。 或者,有一些運行時錯誤會導致您的腳本崩潰並阻止您的方法執行。 可能還有其他一些更奇特的問題,但缺乏更廣泛的背景,我只能推測。
為了確保您的庫在運行任何代碼之前加載,您應該將一個onload
偵聽器附加到您的外部腳本:
mounted () {
let crefPayApi = document.createElement('script')
crefPayApi.onload = () => this.startPayment()
crefPayApi.setAttribute('src', 'https://libs.crefopay.de/3.0/secure-fields.js')
document.head.appendChild(crefPayApi)
},
我找到了解決方案。
進口從來都不是問題。
我只需要忽略 VUEs/eslints 通過 // eslint-disable-next-line 抱怨缺少“this”並且它有效。
因此,似乎應該在沒有“this”的情況下調用外部函數/對象。
let secureFieldsClientInstance =
new SecureFieldsClient('xxxxx',
this.custNo,
this.paymentRegisteredCallback,
this.initializationCompleteCallback,
configuration)
您可以下載腳本,然后使用import
指令通過 webpack 加載腳本。 你可能有類似import Vue from 'vue';
在你的項目中。 這只是從您的節點模塊導入 vue。
對於其他外部腳本,這完全相同,只需使用相對路徑即可。 使用 Vue-CLI 時,您可以import i18n from './i18n';
,其中src
文件夾將包含i18n.js
如果你真的想使用 CDN,你可以像往常一樣添加它,然后將它添加到外部: https ://webpack.js.org/configuration/externals/#externals 使其可以從 webpack 內部訪問
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.