微信小程序实例:开发showToast消息提示接口

        相信在学习小程序文档或者已经创建项目的开发员们,都很清楚小程序的wx.showToast接口只提供了两种icon【success和loading】展示形式,那假如我想要的是不要图标只要存粹的文字提醒呢?或者是我不要微信单方面提供的那种图片呢?想要自己指定的情况呢?这时候要怎么办..


        这几天我根据wx.showToast接口提供的参数,跟着写了个消息提醒模板,

1、如果没有指定icon图标地址,那么就是单纯的显示文字提示,否则就是图标+文字的模式,这时候就要确保icon指向的图片地址是正确的啦。

2、如果没有指定duration提示的延迟时间,默认是1.5s,而我设置的最大值10s是不会自动隐藏消息提示的,除非手动hideToast. 单位:毫秒

3、如果没有指定mask遮罩,默认是跟着显示的,防止触摸穿透

4、如果没有指定cb回调函数,默认直接显示消息提醒,否则可以在等消息提示结束后即刻处理一些其他业务:例如地址跳转,改变订单状态等等

        

以下是整个模板代码结构:        

showToast.wxml::

        

showToast.wxss::

/*showToast*/
.toast-bg {
  position: fixed;
  top: 0;
  bottom: 0;
  z-index: 999999;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, .2);
}
/*水平居中必备样式*/
.toast-center {
  position: fixed;
  z-index: 9999999;
  width: 100%;
  height: 100%;
  text-align: center;
}
.toast {
  display: inline-block;
  padding: 20rpx 40rpx;
  max-width: 600rpx;
  font-size: 28rpx;
  color: #fff;
  background: rgba(0, 0, 0, .5);
  border-radius: 10rpx;
  text-align: center;
}
/*垂直居中必备样式*/
.toast-center::after{
  content: '';
  display: inline-block;
  width: 0;
  height: 100%;
  vertical-align: middle;
}
.toast .toast-icon {
  display: block;
  margin: 0 auto 10rpx auto;
  width: 50rpx;
  height: 50rpx;
}

        

showToast.js::

/*
显示toast提示
title:    提示的内容 必填
icon:     图标,//请指定正确的路径,选填
duration: 提示的延迟时间,单位毫秒,默认:1500, 10000永远存在除非手动清除 选填
mask:     是否显示透明蒙层,防止触摸穿透,默认:true 选填
cb:       接口调用成功的回调函数 选填
 */
function showToast(obj) {
    if (typeof obj == 'object' && obj.title) {
        if (!obj.duration || typeof obj.duration != 'number') { obj.duration = 1500; }//默认1.5s后消失
        var that = getCurrentPages()[getCurrentPages().length - 1];//获取当前page实例
        obj.isShow = true;//开启toast
        if (obj.duration < 10000) {
            setTimeout(function () {
                obj.isShow = false;
                obj.cb && typeof obj.cb == 'function' && obj.cb();//如果有成功的回调则执行
                that.setData({
                    'showToast.isShow': obj.isShow
                });
            }, obj.duration);
        }
        that.setData({
            showToast: obj
        });
    } else {
        console.log('showToast fail:请确保传入的是对象并且title必填');
    }
}
/**
 *手动关闭toast提示
 */
function hideToast() {
    var that = getCurrentPages()[getCurrentPages().length - 1];//获取当前page实例
    if (that.data.showToast) {
        that.setData({
            'showToast.isShow': false
        });
    }
}
module.exports = {
    showToast: showToast,
    hideToast: hideToast
}
*******************************************************************************************************************************  

      接下来是模板的引用和测试:

test.wxml::