技术 · 思考 · 实践 · 成长

首页/微信小程序/正文

微信小程序 wx.showToast 二次封装:成功、错误、Loading 与统一提示

微信小程序313 次阅读

wx.showToast 适合展示短暂、无需用户确认的轻提示,例如“保存成功”“网络异常”。如果每个页面都直接调用,项目很快会出现提示文案、持续时间、错误处理和加载状态不统一的问题。将 Toast、Loading 和确认弹窗集中封装,可以让页面代码更简洁,也方便后续统一调整交互。

一、wx.showToast 基本用法

wx.showToast({
  title: '保存成功',
  icon: 'success',
  duration: 1500,
  mask: false
})

常用参数:

参数说明
title提示内容,应保持简短明确
icon常用 success、error、loading、none,不同基础库版本支持情况可能不同
image自定义图标本地路径,设置后可替代 icon
duration显示时长,单位毫秒
mask是否显示透明蒙层,阻止触摸穿透
success/fail/complete接口调用结果回调

二、Toast、Loading 与 Modal 的使用边界

组件适用场景是否需要用户操作
wx.showToast成功、失败、轻量状态提示不需要
wx.showLoading正在提交、上传、加载等持续过程不需要,但必须主动隐藏
wx.showModal删除、退款、退出等需要确认的操作需要

不要使用长时间 Toast 代替 Loading,也不要用 Toast 询问用户是否确认。职责清晰后,页面交互会更一致。

三、新建统一提示工具

在项目根目录新建:

utils/
└── toast.js

下面使用 ES Module 方式导出,适合现代小程序项目。

四、基础 Toast 封装

// utils/toast.js

const DEFAULT_DURATION = 1800
const MAX_DURATION = 10000

/**
 * 把任意值转换为可展示的非空文本
 * @param {*} value
 * @param {string} fallback
 * @returns {string}
 */
function normalizeText(value, fallback = '操作失败,请稍后重试') {
  if (typeof value === 'string' && value.trim()) {
    return value.trim()
  }
  if (typeof value === 'number') {
    return String(value)
  }
  return fallback
}

/**
 * 限制 duration 范围,避免错误参数造成提示时间异常
 */
function normalizeDuration(duration) {
  const value = Number(duration)
  if (!Number.isFinite(value)) return DEFAULT_DURATION
  return Math.min(MAX_DURATION, Math.max(500, value))
}

/**
 * 通用 Toast
 * @param {string} title 提示文案
 * @param {Object} options 配置
 */
export function toast(title, options = {}) {
  const {
    icon = 'none',
    image,
    duration = DEFAULT_DURATION,
    mask = false
  } = options

  const config = {
    title: normalizeText(title),
    icon,
    duration: normalizeDuration(duration),
    mask: Boolean(mask)
  }

  if (image) {
    config.image = image
  }

  wx.showToast(config)
}

五、成功、错误和普通提示

/**
 * 成功提示:适合保存、提交、复制成功
 */
export function success(title = '操作成功', duration = 1500) {
  toast(title, {
    icon: 'success',
    duration
  })
}

/**
 * 错误提示:使用 none 对低版本基础库更友好,也能展示较长文案
 */
export function error(title = '操作失败,请稍后重试', duration = 2200) {
  toast(title, {
    icon: 'none',
    duration
  })
}

/**
 * 普通信息提示
 */
export function info(title, duration = 1800) {
  toast(title, {
    icon: 'none',
    duration
  })
}

带图标的 Toast 显示空间有限,成功文案应尽量简短。接口错误通常较长,使用 icon: 'none' 更稳妥。

六、防止短时间重复提示

接口拦截器和页面 catch 可能同时提示同一个错误,可以增加简单防重复逻辑:

let lastToastKey = ''
let lastToastTime = 0

/**
 * 相同内容在指定时间内只展示一次
 */
export function once(title, options = {}) {
  const text = normalizeText(title)
  const interval = Number(options.interval || 800)
  const now = Date.now()
  const key = `${options.icon || 'none'}:${text}`

  if (key === lastToastKey && now - lastToastTime < interval) {
    return false
  }

  lastToastKey = key
  lastToastTime = now
  toast(text, options)
  return true
}

防重复只是改善体验,不能用来代替按钮防抖、接口幂等或请求取消。

七、Loading 封装

wx.showLoading 必须配合 wx.hideLoading。多个并发请求如果各自随意隐藏,会出现第一个请求完成后提前关闭其他请求的 Loading。可以使用引用计数:

let loadingCount = 0

/**
 * 显示加载状态
 * @returns {number} 当前 Loading 引用数
 */
export function showLoading(title = '加载中...', mask = true) {
  loadingCount += 1

  if (loadingCount === 1) {
    wx.showLoading({
      title: normalizeText(title, '加载中...'),
      mask: Boolean(mask)
    })
  }

  return loadingCount
}

/**
 * 隐藏一次 Loading 引用
 */
export function hideLoading(force = false) {
  loadingCount = force ? 0 : Math.max(0, loadingCount - 1)

  if (loadingCount === 0) {
    wx.hideLoading()
  }
}

/**
 * 页面卸载或异常恢复时强制清理
 */
export function resetLoading() {
  hideLoading(true)
}

八、用 withLoading 包裹异步任务

/**
 * 自动显示并在 finally 中关闭 Loading
 * @param {Function} task 返回 Promise 的函数
 * @param {Object} options
 */
export async function withLoading(task, options = {}) {
  const {
    title = '加载中...',
    mask = true,
    showError = false,
    errorText = '请求失败,请稍后重试'
  } = options

  showLoading(title, mask)

  try {
    return await task()
  } catch (err) {
    if (showError) {
      error(getErrorMessage(err, errorText))
    }
    throw err
  } finally {
    hideLoading()
  }
}

使用 finally 能确保请求成功、失败或抛出异常时都关闭 Loading。

九、统一提取错误信息

错误可能来自 Error、接口响应或普通字符串,可以统一解析:

/**
 * 从常见错误结构中提取用户可读文案
 */
export function getErrorMessage(err, fallback = '请求失败,请稍后重试') {
  if (!err) return fallback
  if (typeof err === 'string') return normalizeText(err, fallback)

  const candidates = [
    err.message,
    err.errMsg,
    err.msg,
    err.data && err.data.message,
    err.data && err.data.msg,
    err.response && err.response.data && err.response.data.message
  ]

  const message = candidates.find(item => {
    return typeof item === 'string' && item.trim()
  })

  return normalizeText(message, fallback)
}

export function showError(err, fallback) {
  const message = getErrorMessage(err, fallback)
  once(message, {
    icon: 'none',
    duration: 2200
  })
}

不要把服务器堆栈、SQL 错误和敏感字段直接展示给用户。后端应返回可控业务文案,详细错误只写入服务端日志。

十、确认弹窗 Promise 封装

/**
 * 确认弹窗
 * @returns {Promise<boolean>} 确认返回 true,取消返回 false
 */
export function confirm(options = {}) {
  const {
    title = '提示',
    content = '确定执行该操作吗?',
    confirmText = '确定',
    cancelText = '取消',
    confirmColor = '#576b95',
    cancelColor = '#000000',
    showCancel = true
  } = options

  return new Promise((resolve, reject) => {
    wx.showModal({
      title,
      content,
      confirmText,
      cancelText,
      confirmColor,
      cancelColor,
      showCancel,
      success(res) {
        resolve(Boolean(res.confirm))
      },
      fail: reject
    })
  })
}

十一、完整 toast.js

// utils/toast.js
const DEFAULT_DURATION = 1800
const MAX_DURATION = 10000

let lastToastKey = ''
let lastToastTime = 0
let loadingCount = 0

function normalizeText(value, fallback = '操作失败,请稍后重试') {
  if (typeof value === 'string' && value.trim()) return value.trim()
  if (typeof value === 'number') return String(value)
  return fallback
}

function normalizeDuration(duration) {
  const value = Number(duration)
  if (!Number.isFinite(value)) return DEFAULT_DURATION
  return Math.min(MAX_DURATION, Math.max(500, value))
}

export function toast(title, options = {}) {
  const config = {
    title: normalizeText(title),
    icon: options.icon || 'none',
    duration: normalizeDuration(options.duration),
    mask: Boolean(options.mask)
  }
  if (options.image) config.image = options.image
  wx.showToast(config)
}

export function success(title = '操作成功', duration = 1500) {
  toast(title, { icon: 'success', duration })
}

export function error(title = '操作失败,请稍后重试', duration = 2200) {
  toast(title, { icon: 'none', duration })
}

export function info(title, duration = 1800) {
  toast(title, { icon: 'none', duration })
}

export function once(title, options = {}) {
  const text = normalizeText(title)
  const now = Date.now()
  const key = `${options.icon || 'none'}:${text}`
  const interval = Number(options.interval || 800)

  if (key === lastToastKey && now - lastToastTime < interval) return false
  lastToastKey = key
  lastToastTime = now
  toast(text, options)
  return true
}

export function showLoading(title = '加载中...', mask = true) {
  loadingCount += 1
  if (loadingCount === 1) {
    wx.showLoading({ title: normalizeText(title, '加载中...'), mask })
  }
}

export function hideLoading(force = false) {
  loadingCount = force ? 0 : Math.max(0, loadingCount - 1)
  if (loadingCount === 0) wx.hideLoading()
}

export function resetLoading() {
  hideLoading(true)
}

export function getErrorMessage(err, fallback = '请求失败,请稍后重试') {
  if (!err) return fallback
  if (typeof err === 'string') return normalizeText(err, fallback)

  const candidates = [
    err.message,
    err.errMsg,
    err.msg,
    err.data && err.data.message,
    err.data && err.data.msg
  ]
  return normalizeText(
    candidates.find(item => typeof item === 'string' && item.trim()),
    fallback
  )
}

export function showError(err, fallback) {
  once(getErrorMessage(err, fallback), { icon: 'none', duration: 2200 })
}

export async function withLoading(task, options = {}) {
  showLoading(options.title || '加载中...', options.mask !== false)
  try {
    return await task()
  } catch (err) {
    if (options.showError) showError(err, options.errorText)
    throw err
  } finally {
    hideLoading()
  }
}

export function confirm(options = {}) {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title: options.title || '提示',
      content: options.content || '确定执行该操作吗?',
      confirmText: options.confirmText || '确定',
      cancelText: options.cancelText || '取消',
      confirmColor: options.confirmColor || '#576b95',
      showCancel: options.showCancel !== false,
      success: res => resolve(Boolean(res.confirm)),
      fail: reject
    })
  })
}

十二、在页面中使用

import {
  success,
  info,
  showError,
  withLoading,
  confirm
} from '../../utils/toast'

Page({
  async submitForm() {
    try {
      await withLoading(
        () => this.saveForm(),
        { title: '提交中...', mask: true }
      )

      success('提交成功')
      setTimeout(() => wx.navigateBack(), 800)
    } catch (err) {
      showError(err, '提交失败,请稍后重试')
    }
  },

  async deleteItem() {
    const confirmed = await confirm({
      title: '删除确认',
      content: '删除后无法恢复,是否继续?',
      confirmText: '删除',
      confirmColor: '#e64340'
    })

    if (!confirmed) {
      info('已取消删除')
      return
    }

    await withLoading(() => this.requestDelete(), {
      title: '删除中...'
    })
    success('删除成功')
  }
})

十三、结合请求封装使用

// utils/request.js
import { getErrorMessage } from './toast'

export function request(options) {
  return new Promise((resolve, reject) => {
    wx.request({
      ...options,
      success(res) {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          if (res.data && res.data.code === 0) {
            resolve(res.data.data)
            return
          }

          reject(new Error(
            getErrorMessage(res.data, '业务处理失败')
          ))
          return
        }

        reject(new Error(`请求失败(${res.statusCode})`))
      },
      fail(err) {
        reject(new Error(
          getErrorMessage(err, '网络异常,请检查连接')
        ))
      }
    })
  })
}

请求层负责把错误标准化,页面决定是否展示 Toast。这样可以避免请求层和页面层同时弹出两次错误。

十四、CommonJS 项目写法

如果项目仍使用 require,将导出部分改为:

module.exports = {
  toast,
  success,
  error,
  info,
  once,
  showLoading,
  hideLoading,
  resetLoading,
  withLoading,
  getErrorMessage,
  showError,
  confirm
}

页面引用:

const Toast = require('../../utils/toast')

Toast.success('保存成功')
Toast.error('保存失败')
Toast.info('暂无更多数据')

十五、自定义图标

toast('已加入收藏', {
  image: '/assets/icons/favorite.png',
  duration: 1600
})

自定义图标应使用小程序能够访问的本地资源路径,并在真机上检查尺寸、清晰度和深色模式效果。设置 image 后不要再依赖 icon 的展示。

十六、页面卸载时清理 Loading

如果请求没有及时结束,页面离开后可能残留 Loading。可以在页面卸载时兜底清理:

import { resetLoading } from '../../utils/toast'

Page({
  onUnload() {
    resetLoading()
  }
})

如果多个页面或组件同时发起请求,强制清理可能影响其他任务。更完善的项目可以为 Loading 增加 token,而不是只使用全局计数器。

十七、使用 Loading Token 管理并发

const loadingTokens = new Set()

export function openLoading(title = '加载中...') {
  const token = `${Date.now()}_${Math.random()}`
  loadingTokens.add(token)

  if (loadingTokens.size === 1) {
    wx.showLoading({ title, mask: true })
  }
  return token
}

export function closeLoading(token) {
  loadingTokens.delete(token)
  if (loadingTokens.size === 0) {
    wx.hideLoading()
  }
}

Token 方案能确保每个任务只能关闭自己的 Loading,适合组件较多、并发请求复杂的项目。

十八、常见问题

1. Toast 文案显示不完整

带图标的提示空间有限,应缩短文案或改用 icon: 'none'。需要展示大量信息时,应使用页面提示区域或 Modal,而不是不断延长 Toast。

2. showLoading 一直不消失

通常是异常分支没有调用 hideLoading。使用 try/finally 或 withLoading,确保所有执行路径都会关闭。

3. 页面同时弹出两个相同错误

检查请求封装和页面 catch 是否都调用了 showToast。推荐请求层只 reject 标准错误,由页面决定展示;必要时使用 once 防止短时间重复。

4. 连续请求导致 Loading 提前消失

多个请求分别调用 showLoading/hideLoading 会相互覆盖,使用引用计数或 Loading Token 管理并发。

5. success 后立即跳转,看不到提示

可以等待约 500~1000 毫秒再跳转,或在目标页面通过事件/参数展示结果。不要为了等待 Toast 设置过长的固定延迟。

6. error 图标在部分设备表现不同

基础库版本和客户端实现可能存在差异。兼容性优先时,错误提示使用 icon: 'none'。

十九、封装建议

  • Toast 文案保持简短,告诉用户结果而不是技术细节。
  • 接口错误统一转换,页面只处理业务展示。
  • 所有 Loading 都通过 finally 关闭。
  • 危险操作使用 Modal 二次确认。
  • 避免请求层和页面层重复弹窗。
  • 开发工具、真机和不同基础库版本都要测试。
  • 模拟网络慢、请求失败、页面返回和并发请求等异常场景。

二十、总结

对 wx.showToast 进行封装的重点不只是少写几行代码,而是统一成功、错误、加载和确认交互。通过规范错误提取、Loading 引用计数、重复提示抑制和 Promise 封装,可以让页面代码更清晰,也能减少 Loading 不消失、错误重复弹出等常见问题。

官方参考:wx.showToast、wx.showLoading、wx.showModal。

你努力了什么,也就成就了什么,与其羡慕别人,不如蜕变自己。

评论交流

0 条评论 · 支持多级回复
验证码
暂无评论,来说说你的想法吧

相关文章

继续阅读