哪天,正在蚂蚁森林疯狂偷能量的我被boss叫过去,告知我司要作一个线上直播公开课功能的微信小程序,博主第一次写小程序,复习了下文档,看了看腾讯云直播sdk,开工了。
写着写着就发现不对劲了, 这里面wx.showToast
,wx.showModal
,这一类的调用太多了,每次都写一遍太特么麻烦了,就拿wx.showToast
作例子,产品要求是duration
为2000ms,默认值是1500ms,且有时候不须要icon图标,有时候又须要,因此每次都要以下调用javascript
wx.showToast({ title: '建立成功', icon: 'none', duration: 2000 })
不但麻烦,并且代码看着很糟糕,因此博主决定二次封装一下。html
通过博主封装后,代码以下java
// wx.showToast优化前调用 wx.showToast({ title: '建立成功', icon: 'none', duration: 2000 }); // wx.showToast优化后调用 FN.Toast("建立成功");
// wx.showModal优化前调用 wx.showModal({ title: '舒适提示', content: '确认更换帐号吗?', success (res) { if (res.confirm) { console.log('用户点击肯定') } else if (res.cancel) { console.log('用户点击取消') } } }); // wx.showModal优化后调用 FN.Confirm("确认更换帐号吗?") .then(res => { console.log('用户点击肯定') }) .catch(error => { console.log('用户点击取消') });
定义一个公共的public.js
,在里面写上经常使用的方法,用一个常量承载,而后经过module.exports
暴露出去,在须要的地方接收,而其中好比wx.showModal
,wx.login
,这些须要回调来处理的方法,使用了Promise
实现了链式调用。git
文件名:public.js
github
const publicFn = { /** * Loading转圈圈 * @param {nunber} mask - 不传默认不显示透明蒙层 * @param {string} msg - 提示语 默认值:加载中 */ Loading (mask, msg){ let Mask = mask ? true : false; let Msg = msg ? msg : "加载中" wx.showLoading({ title: Msg, mask: Mask }) }, /** * Loading取消转圈圈 */ LoadingOff (){ wx.hideLoading(); }, /** * Toast提示 * @param {string} msg - 提示内容 * @param {string} icon - icon图标 成功success 加载中loading 无样式none * @param {number} time - 提示存在时长 */ Toast (msg, icon, time){ let Icon = icon === 1 ? "success" : "none"; wx.showToast({ title: msg, icon: Icon, duration: time || 2000 }) }, /** * 带确认的提示框 * @param {string} msg - 提示内容 */ Alert (msg){ return new Promise((resolve, reject) => { wx.showModal({ title: '舒适提示', content: msg, showCancel:false, confirmColor:"#007AFF", success (res) { // 此弹窗只有确认键,没有取消键,因此只写了resolve没有reject resolve(res); } }) }) }, /** * 带确认和取消的提示框 * @param {string} msg - 提示内容 */ 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;
使用方法:在你须要调用的地方的js文件顶部引入小程序
//路径根据本身项目文件位置改变 const FN = require('../publicFn/public');
调用语法参考目录2微信小程序
若是看了以为有帮助的,我是@鹏多多,欢迎 点赞 关注 评论;
END服务器
往期文章微信
我的主页ide