1英融,起因
哪天,正在螞蟻森林瘋狂偷能量的我被boss叫過去歇式,告知我司要做一個(gè)線上直播公開課功能的微信小程序驶悟,博主第一次寫小程序,復(fù)習(xí)了下文檔材失,看了看騰訊云直播sdk痕鳍,開工了。
寫著寫著就發(fā)現(xiàn)不對(duì)勁了, 這里面wx.showToast
笼呆,wx.showModal
熊响,這一類的調(diào)用太多了,每次都寫一遍太特么麻煩了诗赌,就拿wx.showToast
做例子汗茄,產(chǎn)品要求是duration
為2000ms,默認(rèn)值是1500ms铭若,且有時(shí)候不需要icon圖標(biāo)洪碳,有時(shí)候又需要,所以每次都要如下調(diào)用
wx.showToast({
title: '創(chuàng)建成功',
icon: 'none',
duration: 2000
})
不但麻煩叼屠,而且代碼看著很糟糕偶宫,所以博主決定二次封裝一下。
2环鲤,優(yōu)化成果
經(jīng)過博主封裝后纯趋,代碼如下
// wx.showToast優(yōu)化前調(diào)用
wx.showToast({
title: '創(chuàng)建成功',
icon: 'none',
duration: 2000
});
// wx.showToast優(yōu)化后調(diào)用
FN.Toast("創(chuàng)建成功");
// wx.showModal優(yōu)化前調(diào)用
wx.showModal({
title: '溫馨提示',
content: '確認(rèn)更換賬號(hào)嗎?',
success (res) {
if (res.confirm) {
console.log('用戶點(diǎn)擊確定')
} else if (res.cancel) {
console.log('用戶點(diǎn)擊取消')
}
}
});
// wx.showModal優(yōu)化后調(diào)用
FN.Confirm("確認(rèn)更換賬號(hào)嗎冷离?")
.then(res => {
console.log('用戶點(diǎn)擊確定')
})
.catch(error => {
console.log('用戶點(diǎn)擊取消')
});
3吵冒,實(shí)現(xiàn)思路
定義一個(gè)公共的public.js
,在里面寫上常用的方法西剥,用一個(gè)常量承載痹栖,然后通過module.exports
暴露出去,在需要的地方接收瞭空,而其中比如wx.showModal
揪阿,wx.login
,這些需要回調(diào)來處理的方法咆畏,使用了Promise
實(shí)現(xiàn)了鏈?zhǔn)秸{(diào)用南捂。
4,完整代碼
文件名:public.js
const publicFn = {
/**
* Loading轉(zhuǎn)圈圈
* @param {nunber} mask - 不傳默認(rèn)不顯示透明蒙層
* @param {string} msg - 提示語 默認(rèn)值:加載中
*/
Loading (mask, msg){
let Mask = mask ? true : false;
let Msg = msg ? msg : "加載中"
wx.showLoading({
title: Msg,
mask: Mask
})
},
/**
* Loading取消轉(zhuǎn)圈圈
*/
LoadingOff (){
wx.hideLoading();
},
/**
* Toast提示
* @param {string} msg - 提示內(nèi)容
* @param {string} icon - icon圖標(biāo) 成功success 加載中l(wèi)oading 無樣式none
* @param {number} time - 提示存在時(shí)長(zhǎng)
*/
Toast (msg, icon, time){
let Icon = icon === 1 ? "success" : "none";
wx.showToast({
title: msg,
icon: Icon,
duration: time || 2000
})
},
/**
* 帶確認(rèn)的提示框
* @param {string} msg - 提示內(nèi)容
*/
Alert (msg){
return new Promise((resolve, reject) => {
wx.showModal({
title: '溫馨提示',
content: msg,
showCancel:false,
confirmColor:"#007AFF",
success (res) {
// 此彈窗只有確認(rèn)鍵旧找,沒有取消鍵溺健,所以只寫了resolve沒有reject
resolve(res);
}
})
})
},
/**
* 帶確認(rèn)和取消的提示框
* @param {string} msg - 提示內(nèi)容
*/
Confirm (msg){
return new Promise((resolve, reject) => {
wx.showModal({
title: '溫馨提示',
content: msg,
cancelColor:"#000000",
confirmColor:"#007AFF",
success (res) {
if (res.confirm) {
resolve(res);
}else if (res.cancel) {
reject(res)
}
}
})
})
},
/**
* 微信登陸 wx.login
*/
wxLogin () {
return new Promise((resolve, reject) => {
wx.login({
success (res) {
if (res.code) {
resolve(res.code)
} else {
reject(res.errMsg);
}
}
})
});
}
}
module.exports = publicFn;
使用方法:在你需要調(diào)用的地方的js文件頂部引入
//路徑根據(jù)自己項(xiàng)目文件位置改變
const FN = require('../publicFn/public');
調(diào)用語法參考目錄2
如果看了覺得有幫助的,我是@鵬多多11997110103钮蛛,歡迎 點(diǎn)贊 關(guān)注 評(píng)論鞭缭;
END
往期文章
個(gè)人主頁