uniapp引入模塊化js文件和非模塊化js文件的四種方式
方式1:引入普通的js文件,如user.js
1.1、屬性和方法都寫在一個變量內(nèi)部
const user={ login:true, isLogin:function(data){ console.log("展示用戶登錄信息") } } export default user;
1.2、也可以單獨寫
function isLogin(data){ ? ? console.log("展示用戶登錄信息") } function getMobile(data){ ? ? console.log("22222222") } ? export default { ? ? isLogin, ? ? getMobile }
在.vue頁面中引用:
<script> ? ? // 絕對路徑,@指向項目根目錄,在cli項目中@指向src目錄 ? ? import userfrom '@/common/user.js'; ? ? // 相對路徑 ? ? import user from '../../common/user.js'; ? ? ? export default { ? ? ? ? ... ? ? ? ? methods: { ? ? ? ? ? ? test(){ ? ? ? ? ? ? ? ? user.isLogin() ?//具體使用 ? ? ? ? ? ? } ? ? ? ? } ? ? } ? </script>
注意
- js 文件不支持使用/開頭的方式引入
方式2:把user.js放在入口文件main.js中,成為全局方法
import user from './common/user.js'; Vue.prototype.$user = user;
在.vue頁面中引用:
<script> ? ? export default { ? ? ? ? ... ? ? ? ? methods: { ? ? ? ? ? ? test(){ ? ? ? ? ? ? ? ? this.$user.isLogin()//具體使用 ? ? ? ? ? ? } ? ? ? ? } ? ? } </script>
方式3:引入第三方的模塊化.js文件
如md5.js加密文件,可以放在common文件夾下,當(dāng)成普通的.js文件引用即可,模塊化的通過module.exports暴露出來成為一個對象:
var exports = createMethod(); if (COMMON_JS) { ? ? module.exports = exports; } else { ? ? root.md5 = exports; ? ? if (AMD) { ? ? ? ? define(function () { ? ? ? ? ? ? return exports; ? ? ? ? }); ? ? } }
在.vue頁面中引用:
<script> ? ? import md5 from '../../common/md5.js'; ? ? export default { ? ? ? ? ... ? ? ? ? methods: { ? ? ? ? ? ? test(){ ? ? ? ? ? ? ? ? let sign = md5(getSignStr(arrKeys, arrValues)).toUpperCase(); ? ? ? ? ? ? } ? ? ? ? } ? ? } </script>
方式4:uniapp開發(fā)的H5,引入第三方的非模塊化.js文件
如nomodule.js,就是純js文件,沒有module.exports暴露出來成為一個對象,這種放在common文件夾下,像上面那樣引入會提示找不到,這時候應(yīng)該把該nomodule.js放在static文件夾下,uniapp發(fā)行H5時static文件下的內(nèi)容不編譯,在并在入口.html文件中引入全局js,在.vue頁面中直接引用就行
4.1、nomodule.js
function isNoModule(data){ ? ? console.log("3333333") }
4.2、 并在入口.html文件中引入全局js
<script charset="utf-8" src="<%= BASE_URL %>static/nomodule.js"></script>
4.3、在.vue頁面中引用
<script> ? ? export default { ? ? ? ? ... ? ? ? ? methods: { ? ? ? ? ? ? test(){ ? ? ? ? ? ? ? ? isNoModule(); ? ? ? ? ? ? } ? ? ? ? } ? ? } </script>
到此這篇關(guān)于uniapp引入模塊化js文件和非模塊化js文件的文章就介紹到這了,更多相關(guān)uniapp引入模塊化js文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue代理請求之Request?failed?with?status?code?404問題及解決
這篇文章主要介紹了vue代理請求之Request?failed?with?status?code?404問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07Vue2.0仿餓了么webapp單頁面應(yīng)用詳細(xì)步驟
本篇文章給大家分享了Vue2.0仿餓了么webapp單頁面應(yīng)用詳細(xì)步驟,有興趣的朋友可以跟著操作下。2018-07-07Element中Upload組件上傳功能實現(xiàn)(圖片和文件的默認(rèn)上傳及自定義上傳)
這篇文章主要介紹了Element中Upload組件上傳功能實現(xiàn)包括圖片和文件的默認(rèn)上傳及自定義上傳,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-01-01詳解vue.js數(shù)據(jù)傳遞以及數(shù)據(jù)分發(fā)slot
本篇文章給大家通過代碼實例分析了vue.js數(shù)據(jù)傳遞以及數(shù)據(jù)分發(fā)slot的相關(guān)知識,有這方面興趣的朋友參考下吧。2018-01-01vue3?Error:Unknown?variable?dynamic?import:?../views/的解
這篇文章主要給大家介紹了關(guān)于vue3?Error:Unknown?variable?dynamic?import:?../views/的解決方案,文中通過圖文以及實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-07-07