各人好啊,这次来分享一下小程序开发的一个使用封装。
配景
先来看下什么是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的长处:
但是原生的这种写法是比力繁琐的,我们很容易在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<string, Function>;
- 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()
- }
- }
- }
复制代码 有效的话,点个赞吧~
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |