微信小程序-封装通用模块

文章目录

微信小程序-封装通用模块

封装toast和modal

js 复制代码
/** 提示消息框 */
function toast({
  title = "数据加载中",
  icon = "none",
  duration = 2000,
  mask = true,
}) {
  wx.showToast({
    title,
    icon,
    duration,
    mask,
  })
}

/** 模拟对话框 */
function modal(opts = {}) {
  const defaultOpts = {
    title: "提示",
    content: "您确定执行该操作吗?",
    confirmColor: "#f3514f",
  }
  return new Promise((resolve) => {
    const options = Object.assign({}, defaultOpts, opts)
    wx.showModal({
      ...options,
      complete({ confirm, cancel }) {
        confirm && resolve(true)
        cancel && resolve(false)
      },
    })
  })
}

// 挂载到 wx 全局对象上
wx.toast = toast
wx.modal = modal

export { toast, modal }

封装storage

js 复制代码
/** 同步存储数据 */
export const setStorage = (key, data) => {
  try {
    wx.setStorageSync(key, data)
  } catch (e) {
    console.error(`存储指定 ${key} 数据时发生了异常`, e)
  }
}

/** 同步获取数据 */
export const getStorage = (key) => {
  try {
    const value = wx.getStorageSync(key)
    if (value) {
      return value
    }
  } catch (e) {
    console.error(`获取指定 ${key} 数据时发生了异常`, e)
  }
}

/** 同步删除指定数据 */
export const removeStorage = (key) => {
  try {
    wx.removeStorageSync(key)
  } catch (e) {
    console.error(`移除指定 ${key} 数据时发生了异常`, e)
  }
}

/** 同步清空全部数据 */
export const clearStorage = () => {
  try {
    wx.clearStorageSync()
  } catch (e) {
    console.error(`清空数据发生了异常`, e)
  }
}

/** 异步存储数据 */
export const asyncSetStorage = (key, data) => {
  return new Promise((resolve) => {
    wx.setStorage({
      key,
      data,
      complete(res) {
        resolve(res)
      },
    })
  })
}

/** 异步获取指定数据 */
export const asyncGetStorage = (key) => {
  return new Promise((resolve) => {
    wx.getStorage({
      key,
      complete(res) {
        resolve(res)
      },
    })
  })
}

/** 异步删除指定数据 */
export const asyncRemoveStorage = (key) => {
  return new Promise((resolve) => {
    wx.removeStorage({
      key,
      complete(res) {
        resolve(res)
      },
    })
  })
}

/** 异步清空全部数据 */
export const asyncClearStorage = () => {
  return new Promise((resolve) => {
    wx.clearStorage({
      key,
      complete(res) {
        resolve(res)
      },
    })
  })
}

封装网络请求

request.js

js 复制代码
class WxRequest {
  /** 默认请求参数 */
  defaultOpts = {
    baseURL: "https://gmall-prod.atguigu.cn/mall-api", //域名
    url: "", // 请求路径
    data: null, // 请求参数
    method: "GET", // 请求方法
    header: {
      // 请求头
      "Content-type": "application/json",
    },
    timeout: 60000, // 超时时间
    isLoading: true, // 是否显示loading
  }

  /** 拦截器 */
  interceptors = {
    // 请求拦截器,发送请求前,可以对请求参数进行更改
    request: (config) => config,
    // 响应拦截器,服务器响应后,可以对数据进行逻辑处理
    response: (response) => response,
  }

  /** 数组,存放请求标识 */
  queue = []

  constructor(options = {}) {
    this.defaultOpts = Object.assign({}, this.defaultOpts, options)
  }

  request(options) {
    this.timeId && clearTimeout(this.timeId)

    options.url = this.defaultOpts.baseURL + options.url
    options = { ...this.defaultOpts, ...options }

    // 使用请求拦截器
    options = this.interceptors.request(options)

    // 如果数组为空,则显示loading
    if (options.isLoading) {
      this.queue.length === 0 && this.showLoading()
      this.queue.push("request")
    }

    return new Promise((resolve, reject) => {
      wx.request({
        ...options,
        success: (res) => {
          console.log("success", res)
          if (res.statusCode === 200) {
            // 第一个参数:目标对象;第二个参数:服务器响应数据;第三个参数:请求配置
            const mergeRes = Object.assign({}, res, {
              config: options,
              isSuccess: true,
            })
            resolve(this.interceptors.response(mergeRes))
          } else {
            wx.showToast({
              title: "服务器异常",
              icon: "error",
            })
          }
        },
        fail: (err) => {
          console.log("fail", err)
          const mergeErr = Object.assign({}, err, {
            config: options,
            isSuccess: false,
          })
          reject(this.interceptors.response(mergeErr))
        },
        complete: () => {
          if (options.isLoading) {
            this.queue.pop()
            this.queue.length === 0 && this.queue.push("request")
            this.timeId = setTimeout(() => {
              this.queue.pop()
              this.queue.length === 0 && this.hideLoading()
              clearTimeout(this.timeId)
            }, 1)
          }
        },
      })
    })
  }

  /** 封装GET请求 */
  get(url, data = {}, config = {}) {
    return this.request(Object.assign({ url, data, method: "GET" }, config))
  }

  /** 封装POST请求 */
  post(url, data = {}, config = {}) {
    return this.request(Object.assign({ url, data, method: "POST" }, config))
  }

  /** 并发请求 */
  all(...promise) {
    console.log("all", promise)
    return Promise.all(promise)
  }

  showLoading() {
    wx.showLoading({
      title: "加载中",
    })
  }

  hideLoading() {
    wx.hideLoading()
  }
}

export default WxRequest

http.js

js 复制代码
import WxRequest from "./request"

// 实例化
const instance = new WxRequest()

// 配置请求拦截器
instance.interceptors.request = (config) => {
  const token = wx.getStorageSync("token")
  if (token) {
    config.header["token"] = token
  }
  return config
}
// 配置响应拦截器
instance.interceptors.response = async (response) => {
  const { isSuccess, data } = response
  if (!isSuccess) {
    wx.showToast({
      title: "网络异常请重试",
      icon: "error",
    })
    return response
  }
  switch (data.code) {
    case 200:
      return data
    case 208:
      wx.showModal({
        title: "提示",
        content: "鉴权失败,请重新登录",
        complete: (res) => {
          if (res.confirm) {
            wx.clearStorage()
            // TODO 跳转登录页面
          }
        },
      })
      return Promise.reject(response)
    default:
      wx.showToast({
        title: "程序出现异常",
        icon: "error",
      })
      return Promise.reject(response)
  }
}

export default instance
相关推荐
软件聚导航20 小时前
「聚小软 AI 助手」技术升级:从数据库检索到 RAG 知识库问答
前端·数据库·mysql·微信小程序·小程序·ai编程·rag
一叶星殇1 天前
微信小程序 Vant Popup 滚动穿透:页面级与组件级解决方案详解
微信小程序·小程序
2601_963869951 天前
【计算机毕业设计】基于微信小程序的点餐传菜系统设计与实现
微信小程序·小程序·课程设计
北漂燕郊杨哥1 天前
VS Code 安装微信小程序 MCP 介绍
vscode·微信小程序·小程序·mcp
维双云2 天前
2026微信小程序开店用哪个平台?长期稳定运营的系统选择方法
微信小程序·小程序
辛迪聊物业数字化2 天前
【智能楼宇系统有什么用?赋能园区高效 节能 安全】
经验分享·安全·微信小程序·php
Coodor2 天前
使用web也可以写NFC微信小程序拉取
前端·微信小程序·小程序·nfc拉起小程序
太阳之神aboluo3 天前
微信小程序 (1) 基础用法
微信小程序·小程序
黑马程序员毕设3 天前
基于B/S架构的“指尖乡味”助农电商小程序系统设计与实现
spring boot·微信小程序·小程序·架构·课程设计·毕设
编程小橘子4 天前
基于微信小程序健康心理测试、设计与实现 (源码+lw+参考文档+核心代码讲解等)
微信小程序·小程序·毕业设计·毕设