toast.js 3.1 KB
/**
 * Toast 提示工具
 *
 * @description 封装 Taro.showToast,提供统一的提示方法
 * @module utils/toast
 */

import Taro from '@tarojs/taro'

/**
 * 显示错误提示
 *
 * @description 显示红色的错误提示(icon: 'none'),默认显示 3 秒
 * @param {string} title - 提示内容
 * @param {number} duration - 显示时长,默认 3000ms
 * @returns {Promise<void>}
 *
 * @example
 * showError('操作失败')
 * showError('网络异常,请重试', 2000)
 */
export function showError(title, duration = 3000) {
  return Taro.showToast({
    title,
    icon: 'none',
    duration
  })
}

/**
 * 显示成功提示
 *
 * @description 显示绿色的成功提示(icon: 'success'),默认显示 2 秒
 * @param {string} title - 提示内容
 * @param {number} duration - 显示时长,默认 2000ms
 * @returns {Promise<void>}
 *
 * @example
 * showSuccess('操作成功')
 * showSuccess('保存成功', 1500)
 */
export function showSuccess(title, duration = 2000) {
  return Taro.showToast({
    title,
    icon: 'success',
    duration
  })
}

/**
 * 显示信息提示
 *
 * @description 显示普通信息提示(icon: 'none'),默认显示 2 秒
 * @param {string} title - 提示内容
 * @param {number} duration - 显示时长,默认 2000ms
 * @returns {Promise<void>}
 *
 * @example
 * showInfo('请先登录')
 * showInfo('加载完成', 1500)
 */
export function showInfo(title, duration = 2000) {
  return Taro.showToast({
    title,
    icon: 'none',
    duration
  })
}

/**
 * 显示加载提示
 *
 * @description 显示加载中提示,需配合 hideLoading 使用
 * @param {string} title - 提示内容,默认 '加载中...'
 * @param {boolean} mask - 是否显示透明蒙层,默认 true
 * @returns {Promise<void>}
 *
 * @example
 * showLoading('提交中...')
 * // 操作完成后
 * hideLoading()
 */
export function showLoading(title = '加载中...', mask = true) {
  return Taro.showLoading({
    title,
    mask
  })
}

/**
 * 隐藏加载提示
 *
 * @description 隐藏由 showLoading 显示的加载提示
 * @returns {Promise<void>}
 *
 * @example
 * hideLoading()
 */
export function hideLoading() {
  return Taro.hideLoading()
}

/**
 * 显示确认对话框
 *
 * @description 显示确认对话框,用户点击确定或取消
 * @param {string} content - 对话框内容
 * @param {string} title - 对话框标题,默认 '提示'
 * @param {Object} options - 其他配置项
 * @param {string} options.confirmText - 确认按钮文字,默认 '确定'
 * @param {string} options.cancelText - 取消按钮文字,默认 '取消'
 * @param {boolean} options.showCancel - 是否显示取消按钮,默认 true
 * @returns {Promise<{confirm: boolean, cancel: boolean}>} 用户选择结果
 *
 * @example
 * const { confirm } = await showConfirm('确定删除吗?')
 * if (confirm) {
 *   // 用户点击了确定
 * }
 */
export function showConfirm(content, title = '提示', options = {}) {
  const { confirmText = '确定', cancelText = '取消', showCancel = true } = options

  return Taro.showModal({
    title,
    content,
    confirmText,
    cancelText,
    showCancel
  })
}