【前端篇】微信小程序ActionSheet封装 -- 封装特性,开发只需要关注功能
创始人
2025-01-10 14:33:24
0

大家好啊,这次来分享一下小程序开发的一个使用封装。

背景

先来看下什么是ActionSheet,参考下图(来源:豆流便签)
在这里插入图片描述
参考原生代码实现:

wx.showActionSheet({     itemList: ["action1", "action2"],     success: (res) => {         if (res.tapIndex === 0) {         	// do action 1         }else if (res.tapIndex === 1){         	// do action 2         }     },     fail: (res) => {         console.log(res.errMsg)     } }) 

action sheet的优点:

  1. 实现简单
  2. 符合微信操作风格

但是原生的这种写法是比较繁琐的,我们很容易在wx.showActionSheet方法里放入大量逻辑代码,层级变的很高。
另一个致命问题,则是如果action是动态的,比如需要根据权限决定是否展示删除功能等,原生api方法需要写大量if else,还需要额外判断动态itemList和执行逻辑之间的关系。
所以这次带来一个开箱即用的action sheet代码。

封装实现

先看下封装后的操作代码:

let actionMenu = new ActionSheetMenu() if (admin) {     actionMenu.addMenu("删除", () => {         // do del logic     }) } actionMenu.addMenu("复制", () => {     // do copy logic }) actionMenu.show() 

可以看到上面的操作,我们不需要关心action sheet的判断逻辑,只需要关注功能关键词和具体实现方法的绑定关系(函数式编程)

好了,最后是封装的代码实现

// action sheet menu的封装,保存sheet name和对应的function export class ActionSheetMenu {     menuMap: Map;     menuList: string[];      constructor() {         this.menuMap = new Map()         this.menuList = []     }      addMenu(key: string, func: Function): void {         this.menuMap.set(key, func)         this.menuList.push(key)     }      show() {         wx.showActionSheet({             itemList: this.getMenuList(),             success: (res) => {                 if (res.tapIndex != -1) {                     this.doFunction(res.tapIndex)                 }             },             fail: (res) => {                 console.log(res.errMsg)             }         })     }      getMenuList(): string[] {         return this.menuList     }      doFunction(index: number) {         if (index < 0 || index >= this.menuList.length) {             throw "index out of range"         }         let menuName = this.menuList[index]         let func = this.menuMap.get(menuName)         if (func) {             func()         }     } } 

有用的话,点个赞吧~

相关内容

热门资讯

随着!wepoker免费辅助器... 随着!wepoker免费辅助器,wepoker免费脚本弱密码(透视)指南书教程(一贯真的有挂)wep...
透视透视!游戏辅助制作器,20... 透视透视!游戏辅助制作器,2025微乐小程序黑科技(开挂)果然真的有挂(有挂解密)-哔哩哔哩1、上手...
昨日!德州透视插件,pokem... 昨日!德州透视插件,pokemmo手机脚本辅助器(透视)秘籍教程(竟然真的有挂)亲,关键说明,pok...
透视普及!werplan透视挂... 透视普及!werplan透视挂(透视)wejoker辅助软件价格,教程阶段(果真有挂)-哔哩哔哩1、...
推出新举措!新玉海楼茶苑辅助器... 推出新举措!新玉海楼茶苑辅助器,wepoker有辅助工具吗,绝活教程(有挂讲解)-哔哩哔哩运新玉海楼...
透视挂透视!阿当比鸡辅助器怎么... 透视挂透视!阿当比鸡辅助器怎么用,新道游房间(开挂)竟然真的是有挂(有挂技巧)-哔哩哔哩;1、阿当比...
最新消息!hhpoker可以控... 最新消息!hhpoker可以控制牌吗,wepoker辅助脚本(透视)指引教程(一直是有挂)hhpok...
透视了解!aapoker怎么设... 透视了解!aapoker怎么设置提高好牌几率(透视)wpk刷入池率脚本,教程指南书(的确有挂)-哔哩...
此事迅速冲上热搜!衢州都莱罗松... 此事迅速冲上热搜!衢州都莱罗松怎么才能赢,pokemmo辅助器手机版下载,绝活儿教程(有挂存在)-哔...
透视免费!熊猫透视辅助无需卡密... 透视免费!熊猫透视辅助无需卡密版,微乐四川麻将辅助器(开挂)一贯有挂(有挂助手)-哔哩哔哩;透视免费...