微信小程序自定義組件---loading組件

在開發微信小程序的過程中,經常會使用到loading動畫,微信自帶的wx.showLoading()與wx.showToast()在使用上非常的方便,但是這個接口也是一個坑,在安卓真機上運行,經常會出現wx.hideLoading()無效的情況,結果就導致loading動畫一直存在,看到微信官方說的是不在onShow和onLoad中調用,還有就是加個延時setTimeout,然而這兩個我都試過了,還是無效,也就是說這個微信官方的bug目前還沒有什麼有效的解決方法,到這裏就決定了,果斷棄坑。

自己寫一個loading組件不香嘛?

下面是實現過程,僅做參考,不足之處還望指出:

wxml文件:

<view class="loading-container"  catchtouchmove="true" hidden="{{!loadingState}}">
  <view class="loading-mask" wx:if="{{maskState}}"></view>
  <view class="loading-main">
    <view class="loading-content">
      <view class="loading-image">
        <image src="../../images/loading.png"></image>
      </view>
      <view class="loading-text">
        {{loadingText}}
      </view>
    </view>
  </view>
</view>

js文件:

// components/rwj-loading/index.js
Component({
  /**
   * 組件的屬性列表
   */
  properties: {
    
  },

  /**
   * 組件的初始數據
   */
  data: {
    loadingState: false,
    maskState: false,
    loadingText: "加載中..."
  },

  /**
   * 組件的方法列表
   */
  methods: {
    show({ mask = false, title = "加載中..." } = {}){
      this.setData({
        loadingState: true,
        maskState: mask,
        loadingText: title
      })
    },
    hide(){
      this.setData({
        loadingState: false
      })
    }
  }
})

wxss文件:

/* components/rwj-loading/index.wxss */
view,page,text{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.loading-container{
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999999;
}
.loading-container .loading-mask{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 9;
  background-color: rgba(0,0,0,0.5);
}
.loading-container .loading-main{
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 99;
}
.loading-container .loading-main .loading-content{
  width: 250rpx;
  height: 250rpx;
  border-radius: 20rpx;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
}
.loading-container .loading-main .loading-content .loading-image{
  width: 150rpx;
  height: 150rpx;
  padding: 40rpx;
  margin-top: 10rpx;
}
.loading-container .loading-main .loading-content .loading-image image{
  width: 100%;
  height: 100%;
  animation: loading 1s linear infinite;
}
@keyframes loading{
from {transform:rotate(0deg);}
to {transform:rotate(360deg);}
}
.loading-container .loading-main .loading-content .loading-text{
  width: 100%;
  padding: 0rpx 20rpx;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #fff;
}

使用方法如下:

wxml中插入組件:
<rwj-loading  id="loading"></rwj-loading>

js調用:
this.selectComponent("#loading").show();
this.selectComponent("#loading").hide();

補充:建議在app.json中全局引入。

優化:我想像wx.showLoading()那樣直接寫js控制顯示隱藏,使用組件的話還需要插入到wxml才能使用,在使用便捷方面感覺還是不如微信官方的接口的,希望哪位大神可以提供一下思路。

發佈了73 篇原創文章 · 獲贊 14 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章