微信小程序 --- 通用模块封装(showToast,showModal ,本地存储)

284 阅读7分钟

微信小程序 --- 通用模块封装(showToast,showModal ,本地存储)

目录

[TOC]

01. 为什么进行模块封装

在进行项目开发的时候,我们经常的会频繁的使用到一些 API,

例如: wx.showToast()wx.showModal() 等消息提示 API ,这些 API 的使用方法如下:

wx.showToast({
  title: '消息提示框', // 提示的内容
  icon: 'success',   // 提示图标
  duration: 2000,	 // 提示的延迟时间
  mask: true		 // 是否显示透明蒙层,防止触摸穿透
})
 
wx.showModal({
  title: '提示', // 提示的标题
  content: '您确定执行该操作吗?', // 提示的内容
  confirmColor: '#f3514f', // 确定按钮的样式
  // 接口调用结束的回调函数(调用成功、失败都会执行)
  complete({ confirm, cancel }) {
    if (confirm) {
      console.log('用户点击了确定')
      return
    }
 
    if (cancel) {
      console.log('用户点击了取消')
    }
  }
})

如果每次使用的时候,都直接调用这些 API ,会导致代码很冗余,为了减少了代码冗余,我们需要将这些 API 封装成公共方法,封装后的使用方式如下:

// wx.showToast() 封装后的调用方式
toast()
toast({ title: '数据加载失败....', mask: true })
 
// wx.showModal() 封装后的调用方式
const res = await modal({
  title: '提示',
  content: '鉴权失败,请重新登录 ?'
})
 
// 用户点击了确定
if (res) { ... } else { ... }

可以看到封装后方法,极大简化 API 的调用,

同时,我们在后续还会进行网络通用模块的封装,如果直接进行封装难度比较大,

进行通过模块的封装,也是为后续 [网络请求封装] 做铺垫。

02. 消息提示模块封装

基本使用:

wx.showToast() 消息提示框是在项目中频繁使用的一个小程序 API ,常用来给用户进行消息提示反馈。使用方式如下:

wx.showToast({
  title: '消息提示框', // 提示的内容
  icon: 'success',   // 提示的图标,success(成功)、error(失败)、loading(加载)、none(不显示图标)
  duration: 2000,	 // 提示的延迟时间
  mask: true		 // 是否显示透明蒙层,防止触摸穿透
})

封装思路:

  1. 创建一个 toast 方法对 wx.showToast() 方法进行封装

  2. 调用该方法时,传递对象作为参数

  • 如果没有传递任何参数,设置一个空对象 {} 作为默认参数

  • 从对象中包含 titleicondurationmask 参数,并给参数设置默认值

  1. 在需要显示弹出框的时候调用 toast 方法,并传入相关的参数,有两种参数方式:
  • 不传递参数,使用默认参值
  • 传入部分参数,覆盖默认的参数

调用方式:

新封装的模块,我们希望有两种调用的方式:

模块化的方式导入使用

import { toast } from './extendApi'
 
toast()
toast({ title: '数据加载失败....', mask: true })

将封装的模块挂载到 wx 全局对象身上

wx.toast()
wx.toast({ title: '数据加载失败....', mask: true })

实现步骤:

  1. utils 目录下新建 extendApi.js 文件
  2. wx.showToast() 方法进行封装

落地代码:

➡️ utils/extendApi.js

/**
 * @description 封装消息提示组件
 * @param {*} title 提示的内容
 * @param {*} icon 图标
 * @param {*} duration 提示的延迟时间
 * @param {*} mask 是否显示透明蒙层,防止触摸穿透
 */
const toast = ({ title = '数据加载中', icon = 'none', mask = true, duration = 3000 } = {}) => {
  wx.showToast({
    title,
    icon,
    mask,
    duration
  })
}
 
// 在 wx 全局对象上封装 toast 方法
// 调用 API 方式:
// 1. 在入口文件 app.js 导入封装的模块  import './utils/extendApi'
// 2. 调用封装的方法:wx.toast('')
wx.toast = toast
 
// 模块化的方式使用
// 调用 API 方式:
// 1. 导入该文件:import { toast } from '../utils/extendApi'
// 2. 调用封装的方法:toast('')
export { toast }

➡️ app.js

import { toast } from './utils/extendApi'
 
App({
  onLaunch() {
 
    // 第一种调用方式:不传入任何参数
    toast()
 
    // 第二种调用方式:传入部分参数
    toast({ title: '数据加载失败....', mask: true })
    
    // 第三种调用方式:传入全部的参数
    toast({ title: '数据加载失败....', mask: true })
    
  }
})
03. 模态对话框封装

基本使用:

wx.showModal() 模态对话框也是在项目中频繁使用的一个小程序 API ,通常用于向用户询问是否执行一些操作,例如:询问用户是否真的需要退出、是否确认删除等等

wx.showModal({
  title: '提示', // 提示的标题
  content: '您确定执行该操作吗?', // 提示的内容
  confirmColor: '#f3514f',
  // 接口调用结束的回调函数(调用成功、失败都会执行)
  complete({ confirm, cancel }) {
    confirm && console.log('点击了确定')
    cancel && console.log('点击了取消')
  }
})

封装思路:

  1. wx.showModal() 方法进行封装, 封装后的新方法叫 modal
  2. 调用该方法时,传递对象作为参数,对象的参数同 wx.showModal() 参数一致
  3. 封装的 modal 方法的内部通过 Promise 返回用户执行的操作(确定和取消,都通过 resolve 返回)
  4. 在需要显示模态对话框的时候调用 modal 方法,并传入相关的参数,有三种调用方式:
  • 不传递参数,使用默认参数
  • 传递参数,覆盖默认的参数

调用方式:

新封装的本地存储模块,我们依然希望有两种调用的方式:

  1. 模块化的方式导入使用
  2. 将封装的模块挂载到 wx 全局对象身上

实现步骤:

  1. extendApi.js 文件中新建 modal 方法,方法内部
  2. modal 方法,方法内部用来处理封装的逻辑

落地代码:

➡️ utils/extendApi.js

// coding...
 
/**
 * @description 封装 wx.showModal  方法
 * @param {*} options 同 wx.showModal 配置项
 */
export const modal = (options = {}) => {
  // 使用 Promise 处理 wx.showModal 的返回结果
  return new Promise((resolve) => {
 
    // 默认的参数
    const defaultOpt = {
      title: '提示',
      content: '您确定执行该操作吗?',
      confirmColor: '#f3514f',
    }
 
    // 将传入的参数和默认的参数进行合并
    const opts = Object.assign({}, defaultOpt, options)
 
    wx.showModal({
      // 将合并的参数赋值传递给 showModal 方法
      ...opts,
      complete({ confirm, cancel }) {
        // 如果用户点击了确定,通过 resolve 抛出 true
        // 如果用户点击了取消,通过 resolve 抛出 false
        confirm && resolve(true)
        cancel && resolve(false)
      }
    })
  })
}
 
// 在 wx 全局对象上封装 myToast 方法
// 调用 API 方式:
// 1. 在入口文件 app.js 导入封装的模块  import './utils/extendApi'
// 2. 调用封装的方法:wx.toast('')
wx.toast = toast
+ wx.modal = modal
 
// 模块化的方式使用
// 调用 API 方式:
// 1. 导入该文件:import { toast } from '../utils/extendApi'
// 2. 调用封装的方法:toast('')
+ export { toast, modal }

➡️ app.js

import { modal } from './utils/extendApi'
 
App({
  async onLaunch() {
      
    // 第一种调用方式:不传入任何参数
    // 不使用任何参数,使用默认值
    const res = await modal()
    console.log(res)
 
    // 第二种调用方式:更改默认配置
    const res = await modal({
      content: '鉴权失败,请重新登录',
      showCancel: false
    })
    console.log(res)
  }
})
04. 封装本地存储 API

思路分析:

在小程序中,经常需要将一些数据存储到本地,方便多个页面的读取使用,例如:将用户的登录状态、用户的个人信息存储到本地。

小程序提供了同步、异步两类 API 来实现本地存储操作。例如: wx.setStorageSyncwx.setStorage 等方法

try {
  wx.setStorageSync(key, value)
} catch (err) {
  console.error(`存储指定 ${key} 数据发生错误:`, err)
}
 
wx.setStorage({
  key: 'key',
  data: 'data',
  success (res) => {},
  fail (err) => {}
})

如果直接使用这些 API,会比较麻烦,通常情况下,我们需要对本地存储的方法进行封装。

实现步骤:

  1. utils 目录下新建 storage.js 文件
  2. 在该文件中,封装对本地数据进行 存储、获取、删除、清除的方法

落地代码:

➡️ utils/storage.js

/**
 * @description 存储数据
 * @param {*} key 本地缓存中指定的 key
 * @param {*} value 需要缓存的数据
 */
export const setStorage = (key, value) => {
  try {
    wx.setStorageSync(key, value)
  } catch (e) {
    console.error(`存储指定 ${key} 数据发生错误:`, e)
  }
}
 
/**
 * @description 从本地读取对应 key 的数据
 * @param {*} key 
 */
export const getStorage = (key) => {
  try {
    const value = wx.getStorageSync(key)
    if (value) {
      return value
    }
  } catch (e) {
    console.error(`获取指定 ${key} 数据发生错误:`, e)
  }
}
 
/**
 * @description 从本地移除指定 key 数据
 * @param {*} key 
 */
export const removeStorage = (key) => {
   try {
     wx.removeStorageSync(key)
   } catch (err) {
     console.error(`移除指定 ${key} 数据发生错误:`, e)
   }
}
 
/**
 * @description 从本地清空全部的数据
 */
export const clearStorage = () => {
  try {
    wx.clearStorageSync()
  } catch (e) {
    console.error("清空本地存储时发生错误:", e);
  }
}
05. 拓展:封装异步存储API+优化代码

思路分析:

使用 Promise 封装异步存储 API

wx.setStorage({
  key: 'key',
  data: 'data',
  success(res) {},
  fail(err) {},
  complete(res) {}
})

使用方式:

// 异步将数据存储到本地
asyncSetStorage(key, data)
 
// 异步从本地读取指定 key 的数据
asyncGetStorage(key)
 
// 异步从本地移除指定 key 的数据
asyncRemoveStorage(key)
 
// 异步从本地移除、清空全部的数据
asyncClearStorage()

落地代码:

➡️ utils/storage.js

 
/**
 * @description 将数据存储到本地 - 异步方法
 * @param {*} key 本地缓存中指定的 key
 * @param {*} data 需要缓存的数据
 */
export const asyncSetStorage = (key, data) => {
  return new Promise((resolve) => {
    wx.setStorage({
      key,
      data,
      complete(res) {
        resolve(res)
      }
    })
  })
}
 
/**
 * @description 从本地读取指定 key 的数据 - 异步方法
 * @param {*} key
 */
export const asyncGetStorage = (key) => {
  return new Promise((resolve) => {
    wx.getStorage({
      key,
      complete(res) {
        resolve(res)
      }
    })
  })
}
 
/**
 * @description 从本地移除指定 key 的数据 - 异步方法
 * @param {*} key
 */
export const asyncRemoveStorage = (key) => {
  return new Promise((resolve) => {
    wx.removeStorage({
      key,
      complete(res) {
        resolve(res)
      }
    })
  })
}
 
/**
 * @description 从本地移除、清空全部的数据 - 异步方法
 */
export const asyncClearStorage = () => {
  return new Promise((resolve) => {
    wx.clearStorage({
      complete(res) {
        resolve(res)
      }
    })
  })
}