在开发微信小程序的过程中,经常会使用到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才能使用,在使用便捷方面感觉还是不如微信官方的接口的,希望哪位大神可以提供一下思路。