如何将外部 JS 脚本添加到 VueJS 组件?

新手上路,请多包涵

我必须为支付网关使用两个外部脚本。

现在两者都放在 index.html 文件中。

但是,我不想在一开始就加载这些文件。

只有在用户打开特定组件( using router-view )时才需要支付网关。

有没有办法做到这一点?

谢谢。

原文由 Gijo Varghese 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 829
2 个回答

解决此问题的一种简单有效的方法是将外部脚本添加到组件的 vue mounted() 中。我将使用 Google Recaptcha 脚本向您说明:

 <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

原文由 mejiamanuel57 发布,翻译遵循 CC BY-SA 4.0 许可协议

我已经下载了一些带有自定义 js 文件和 jquery 的 HTML 模板。我必须将这些 js 附加到我的应用程序。并继续使用 Vue。

找到了这个插件,这是一种通过 CDN 和静态文件添加外部脚本的干净方法 https://www.npmjs.com/package/vue-plugin-load-script

 // local files
// you have to put your scripts into the public folder.
// that way webpack simply copy these files as it is.
Vue.loadScript("/js/jquery-2.2.4.min.js")

// cdn
Vue.loadScript("https://maps.googleapis.com/maps/api/js")

原文由 PJ3 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题