7

如何在vue组件内引用外部js脚本?

 3 years ago
source link: http://coding2live.com/detail/80/%E5%A6%82%E4%BD%95%E5%9C%A8vue%E7%BB%84%E4%BB%B6%E5%86%85%E5%BC%95%E7%94%A8%E5%A4%96%E9%83%A8js%E8%84%9A%E6%9C%AC%EF%BC%9F
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

如何在vue组件内引用外部js脚本?

coding2live 2021-02-05 16:29:14 0 140 javascript, vue.js, vuejs2, vue-component, vue-router

为了实现一个支付功能,我需要引入两个外部的js脚本。

我把它们都放到了index.html文件中。

但是,我不想一开始就加载这些文件。因为支付功能只在用户打开特定组件时才会用到(项目中用到了router-view)。

有什么办法实现这个吗?

以下答案仅供参考

有一个简单高效的方法可以实现你的需求。

就是在你的组件的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>
电报频道: 划水摸鱼爱好者 Q Q 群聊: 993137424 站长微信: read-write-code

友情链接 添加友链请发送邮件至:onebookman#foxmail.com


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK