1、新建toastUtil.js文件,代码如下:
/**
* Toast工具类,封装uni.showToast和uni.hideToast
* 提供更灵活的Toast显示控制
*/
export default {
/**
* 显示Toast提示
* @param {Object} options - Toast配置项
* @param {string} options.title - 提示内容
* @param {string} [options.icon='none'] - 图标,支持none、success、loading、error
* @param {number} [options.duration=2000] - 显示时长,单位ms
* @param {string} [options.position='center'] - 位置,支持top、center、bottom
* @param {string} [options.mask=false] - 是否显示透明蒙层,防止触摸穿透
*/
show(options) {
// 先隐藏可能存在的Toast
this.hide();
// 默认配置
const defaultOptions = {
title: '',
icon: 'none',
duration: 2000,
position: 'center',
mask: false
};
// 合并配置
const toastOptions = { ...defaultOptions, ...options };
// 调用uni的showToast
uni.showToast(toastOptions);
// 如果是加载中图标,不自动关闭(需要手动调用hide)
if (toastOptions.icon === 'loading') {
// 清除可能存在的定时器
if (this.timer) {
clearTimeout(this.timer);
}
} else {
// 设置自动关闭定时器
this.timer = setTimeout(() => {
this.hide();
}, toastOptions.duration);
}
},
/**
* 隐藏Toast
*/
hide() {
uni.hideToast();
// 清除定时器
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
},
/**
* 快捷显示成功提示
* @param {string} title - 提示内容
* @param {number} [duration=2000] - 显示时长
*/
success(title, duration = 2000) {
this.show({
title,
icon: 'success',
duration
});
},
/**
* 快捷显示错误提示
* @param {string} title - 提示内容
* @param {number} [duration=2000] - 显示时长
*/
error(title, duration = 2000) {
this.show({
title,
icon: 'error',
duration
});
},
/**
* 快捷显示加载提示
* @param {string} [title='加载中'] - 提示内容
* @param {boolean} [mask=true] - 是否显示蒙层
*/
loading(title = '加载中', mask = true) {
this.show({
title,
icon: 'loading',
mask
});
}
};
2、在需要使用的页面引入:
import toastUtil from '@/utils/toastUtil.js';
3、基本使用:
// 显示普通提示
toastUtil.show({
title: '操作成功',
duration: 3000
});
// 显示成功提示
toastUtil.success('提交成功');
// 显示错误提示
toastUtil.error('操作失败,请重试');
// 显示加载提示(需要手动关闭)
toastUtil.loading('正在加载数据...');
// 关闭Toast(特别是用于关闭加载提示)
setTimeout(() => {
toastUtil.hide();
}, 2000);
4、这个封装具有以下特点:
- 提供了统一的调用方式,避免重复配置
- 支持自动关闭和手动关闭两种模式
- 针对不同场景提供了快捷方法(success/error/loading)
- 自动处理定时器,避免内存泄漏
- 兼容 UniApp 的多端运行环境