如何将外部JS脚本添加到VueJS组件
我必须对支付网关使用两个外部脚本.现在,两者都放在index.html
文件中.但是,我不想在一开始就加载这些文件.仅当用户打开特定组件(using router-view
)时才需要支付网关.
I've to use two external scripts for the payment gateways. Right now both are put in the index.html
file. However, I don't want to load these files at the beginning itself. The payment gateway is needed only in when user open a specific component (using router-view
).
反正有实现这一目标的方法吗?
Is there anyway to achieve this?
一种简单有效的解决方法,是将外部脚本添加到组件的vue mounted()
中.我将用 Google Recaptcha 脚本向您说明:
A simple and effective way to solve this, it's by adding your external script into the vue mounted()
of your component. I will illustrate you with the Google Recaptcha script:
<template>
.... your HTML
</template>
<script>
export default {
data: () => ({
......data of your component
}),
mounted() {
let recaptchaScript = document.createElement('script')
recaptchaScript.setAttribute('src', 'https://www.google.com/recaptcha/api.js')
document.head.appendChild(recaptchaScript)
},
methods: {
......methods of your component
}
}
</script>
来源: https ://medium.com/@lassiuosukainen/how-to-include-a-script-tag-on-a-vue-component-fe10940af9e8