uniapp 或 vue 封裝公共方法
阿新 • • 發佈:2021-01-29
專案中,如果頻繁用到某些方法的時候,我們肯定要去想到封裝,不然程式碼冗餘,看上去非常不美觀,下面,我簡單封裝個例子,希望大家都能主動去封裝自己常用的方法
1.我一般喜歡把封裝的js檔案放在utils靜態資料夾下 如圖:
2.舉個例子 我封裝手機號碼的驗證格式
//校驗手機格式
function checkMobile(mobile) {
return RegExp(/^1[34578]\d{9}$/).test(mobile);
}
//一定要宣告暴露函式,可以被引用
module.exports = {
checkMobile
}
3.用的頁面引入當前檔案
4.如何使用
if (!encap.checkMobile(self.form.phone)) {
console.log(self.form.phone)
uni.showToast({
title: '電話號碼格式錯誤',
icon: 'none', //不要圖示
duration: 2000 //2秒後消失
})
return;
}
結束