微信小程序自定義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
        })
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容