微信小程序自定义toast多行文本提示 并配置全局使用

1、自定义组件toast-text-more结构


企业微信截图_17026247172841.png

toast-text-more.wxml

<!-- 多行文本提示 默认一行最多15个字 最多显示3行 -->
<view class='toast-mask' hidden='{{hidden}}'>
  <view class='toast-body'>
    <view class="toast-text {{!isShowAllData?'toast-all-text':''}}">{{title}}</view>
  </view>
</view>
// component/toast-text-more/toast-text-more.ts wt

let toastTimer = null;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
  },

  /**
   * 组件的初始数据
   */
  data: {
    title: '提示',//默认显示的提示文本
    duration: '1000',//提示显示时间
    hidden: true,//是否显示
    isShowAllData: false//是否显示全部数据,默认false: 最多显示3行,显示不开显示...
  },
  lifetimes: {
    attached() {
      wx.$event.on('changeToastMore', this, this.showToast)
    },
    detached() {
      wx.$event.remove('changeToastMore', this)
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 展示弹框
    showToast: function (options) {
      if (toastTimer) {
        clearTimeout(toastTimer);
      }
      this.setData({
        hidden: false,
        isShowAllData: options?.isShowAllData ?? this.data.isShowAllData,
        title: options?.title ?? this.data.title
      });

      let _this = this;
      toastTimer = setTimeout(() => {
        _this.hideToast();
        toastTimer = null;
      }, options?.duration ?? this.data.duration);
    },
    // 关掉弹框
    hideToast: function () {
      this.setData({
        hidden: true,
      });
    }
  }
})

/* component/toast-text-more/toast-text-more.less wt */

.toast-mask {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .toast-body {
    position: absolute;
    top: 40%;
    max-width: 480rpx;
    background: #4c4c4c;
    border-radius: 16rpx;
    padding: 20rpx 30rpx;

    .toast-text {
      color: white;
      font-size: 32rpx;
      text-align: center;
    }

    .toast-all-text {
      display: -webkit-box;
      word-break: break-all;
      text-overflow: ellipsis;
      overflow: hidden;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3; //设置 需要显示的行数
    }
  }
}

2、toast-more-text.js是utils里的全局方法


企业微信截图_1702624875298.png

企业微信截图_17026252907975.png
//自定义toast 多行文本提示 全局事件
function showToastMore(options) {
  wx.$event.emit('changeToastMore', options);
}
wx.$showToastMore = showToastMore;
module.exports = wx.$showToastMore;

3、在app.ts和app.json里


企业微信截图_17026248882480.png

企业微信截图_17026245856203.png

企业微信截图_17026245493976.png

全局引用
全局引用js文件.png

注意:eventBus文件没有放出来,见上一篇。

4、在你要用的页面的js里用法示例:


企业微信截图_1702624690205.png

企业微信截图_17026246457501.png

企业微信截图_17026246133331.png
    wx.$showToastMore({
          title: '多行文本显示很多很多多行文本显示很多很多多行文本显示很多很多多行文本显示很多很多多行文本显示很多很多',
          duration: 2000
        })
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容