【前端篇】微信小程序ActionSheet封装 -- 封装特性,开发只须要关注功能 ...

打印 上一主题 下一主题

主题 857|帖子 857|积分 2571

各人好啊,这次来分享一下小程序开发的一个使用封装。
配景

先来看下什么是ActionSheet,参考下图(来源:豆流便签)

参考原生代码实现:
  1. wx.showActionSheet({
  2.     itemList: ["action1", "action2"],
  3.     success: (res) => {
  4.         if (res.tapIndex === 0) {
  5.                 // do action 1
  6.         }else if (res.tapIndex === 1){
  7.                 // do action 2
  8.         }
  9.     },
  10.     fail: (res) => {
  11.         console.log(res.errMsg)
  12.     }
  13. })
复制代码
action sheet的长处:

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

先看下封装后的操作代码:
  1. let actionMenu = new ActionSheetMenu()
  2. if (admin) {
  3.     actionMenu.addMenu("删除", () => {
  4.         // do del logic
  5.     })
  6. }
  7. actionMenu.addMenu("复制", () => {
  8.     // do copy logic
  9. })
  10. actionMenu.show()
复制代码
可以看到上面的操作,我们不须要关心action sheet的判断逻辑,只须要关注功能关键词和具体实现方法的绑定关系(函数式编程)
好了,末了是封装的代码实现
  1. // action sheet menu的封装,保存sheet name和对应的function
  2. export class ActionSheetMenu {
  3.     menuMap: Map<string, Function>;
  4.     menuList: string[];
  5.     constructor() {
  6.         this.menuMap = new Map()
  7.         this.menuList = []
  8.     }
  9.     addMenu(key: string, func: Function): void {
  10.         this.menuMap.set(key, func)
  11.         this.menuList.push(key)
  12.     }
  13.     show() {
  14.         wx.showActionSheet({
  15.             itemList: this.getMenuList(),
  16.             success: (res) => {
  17.                 if (res.tapIndex != -1) {
  18.                     this.doFunction(res.tapIndex)
  19.                 }
  20.             },
  21.             fail: (res) => {
  22.                 console.log(res.errMsg)
  23.             }
  24.         })
  25.     }
  26.     getMenuList(): string[] {
  27.         return this.menuList
  28.     }
  29.     doFunction(index: number) {
  30.         if (index < 0 || index >= this.menuList.length) {
  31.             throw "index out of range"
  32.         }
  33.         let menuName = this.menuList[index]
  34.         let func = this.menuMap.get(menuName)
  35.         if (func) {
  36.             func()
  37.         }
  38.     }
  39. }
复制代码
有效的话,点个赞吧~

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

何小豆儿在此

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表