vue优雅的引入第三方Js

Posted by Azukin on June 15, 2022

将第三方包CvNetVideo.js放在public中

全局引入

1
2
<!-- 常用的方式是在public/index.html引入 -->
<script>document.write('<script src="./CvNetVideo.js"><\/script>');</script>

优雅的引入

创建一个Import.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export function CvNetVideoImport() {
  return new Promise(function (resolve, reject) {
    if (window.CvNetVideo == null || window.CvNetVideo == undefined) {
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = './CvNetVideo.js' // 导入静态文件public/CvNetVideo.js
      script.onerror = reject
      document.body.appendChild(script)
      script.onload = () => {
        resolve(window.CvNetVideo)
      }
    } else {
      resolve(window.CvNetVideo)
    }
  })
}

在需要使用的.vue中引入使用

1
2
3
4
5
6
7
8
9
10
import { CvNetVideoImport } from '@/utils/Import'
export default {
    methods:{
        init(){
            CvNetVideoImport().then(CvNetVideo => {
                console.log(CvNetVideo)
            })
        }
    }
}