方法一:異步加載第三方庫
在我們的vue工程中新建如下路徑:src/utils/index.js,在index.js中實現如下方法:
export function loadScript(url) { let isLoaded = false; return new Promise((resolve,reject) => { if(isLoaded) { resolve(); return true; } let script = document.createElement('script'); script.type = 'text/javascript'; script.charset = 'utf-8'; script.async = true; script.src = url; script.onerror = reject; script.onload = function () { isLoaded = true; resolve(); } document.head.appendChild(script); }) }
我們在static下面創建一個lib.js文件存放普通的方法:
function sum(a,b) { return a + b; }
那么我們在某一個vue頁面引入這個loadScript,在lib.js加載完成后再執行后續的操作,如下vue頁面代碼:
<template> <div> 其他組件內容 </div> </template> <script> import {loadScript} from '@/utils/index.js'; export default { data() { return { } }, created() { loadScript('./static/lib.js').then(() => { console.log(sum(2,3)) }) }, methods: { } } </script> <style> </style>
當然也可以使用插件來實現。
- vue框架使用:vue-plugin-load-script
- react框架使用:react-load-script
方式二:index.html靜態模板script標簽引入
<script type="text/javascript" src="./static/lib.js"></script>
然后在其他vue頁面就可以全局調用lib中的方法了。