【前端篇】微信小程序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()         }     } } 

有用的话,点个赞吧~

相关内容

热门资讯

八分钟辅助!拱趴大菠萝万能挂图... 八分钟辅助!拱趴大菠萝万能挂图解,如何下载wpk透视版,妙招教程(有挂秘笈)1、打开软件启动之后找到...
第9分钟辅助!wepoker辅... 第9分钟辅助!wepoker辅助插件功能,hhpoker辅助软件是真的么,项目教程(有挂头条)该软件...
第五分钟辅助!wpk作弊最怕三... 第五分钟辅助!wpk作弊最怕三个东西,wepoker免费脚本,手册教程(有挂总结)1、下载好wpk作...
9分钟辅助!德普之星透视辅助,... 9分钟辅助!德普之星透视辅助,wepokerplus辅助,方式教程(有挂透明挂)1、用户打开应用后不...
1分钟辅助!wepoker透视... 1分钟辅助!wepoker透视挂底牌,hhpoker透视脚本视频,方案教程(今日头条)1、玩家可以在...
第三分钟辅助!如何下载德普之星... 第三分钟辅助!如何下载德普之星辅助软件,智星菠萝有挂吗,模块教程(有挂教程)如何下载德普之星辅助软件...
9分钟辅助!hhpoker作弊... 9分钟辅助!hhpoker作弊码,xpoker辅助工具,教程书教程(有挂分析)运xpoker辅助工具...
第4分钟辅助!pokemmo手... 第4分钟辅助!pokemmo手机脚本,werplan辅助软件,总结教程(真是有挂)1、首先打开pok...
9分钟辅助!德州真人透视脚本,... 9分钟辅助!德州真人透视脚本,pokemmo脚本辅助器下载,妙计教程(存在有挂)1、超多福利:超高返...
第五分钟辅助!德普之星怎么设置... 您好,德普之星怎么设置埋牌这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...