微信小程序封装全局加载动画loading

思路

封装全局加载动画的核心思路就是在每个页面加载数据时弹出加载动画,在数据加载完成后关闭动画。由于需要在所有页面中使用,我们需要将加载动画封装成一个全局组件,供所有页面调用。

第一步:创建Loading组件

在components新建Loading组件,用来展示动画,并在组件中实现开启和结束动画的方法。

wxml代码:

javascript 复制代码
<view class='loading-mask' wx:if="{{showLoading}}">
  <view class='loading-content'>
    <image class='loading-image' src='/img/loading.gif'></image>
  </view>
</view>

js代码:

javascript 复制代码
// components/loading/loading.js
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    // 是否显示loading
    showLoading: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 开启动画
    show() {
      this.setData({
        showLoading: true
      });
    },
    // 关闭动画
    hide() {
      this.setData({
        showLoading: false
      });
    }
  }
})

CSS样式:

javascript 复制代码
.loading-mask {
  width: 100vw;
  height: 100vh;
	position: fixed;
	top: 0;
	left: 0;
}
.loading-content{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  width: 160rpx;
  height: 160rpx;
}
.loading-content image{
 width: 100%;
 height: 100%;
}

第二步:在utils\util.js下封装控制方法,导出

设定全局方法loadingShow和loadingHide来显示和隐藏Loading组件。

javascript 复制代码
const loadingShow = function () {
  getCurrentPages()[0].selectComponent("#loading").show()
}
const loadingHide = function () {
  getCurrentPages()[0].selectComponent("#loading").hide()
}
                      
module.exports = {	
  loadingShow,
  loadingHide
}

第三步:在app.json中注册组件

javascript 复制代码
"usingComponents": {
    "Loading": "/components/loading/loading"
  }

第四步:在需要用到加载动画的地方放置组件

比如:index.html

javascript 复制代码
<Loading id="loading"></Loading>

第五步:在app.js中使用Loading组件

javascript 复制代码
导入 import { loadingShow, loadingHide} from "./utils/util";
然后在封装的ajax调用时使用 loadingShow()
调用结束 loadingHide()

注意:在onLaunch调用无效
确保调用 selectComponent 的时机是在组件渲染完成之后,可以在 onReady 或 onLoad 生命周期方法中使用。

相关推荐
spmcor8 小时前
微信小程序 setStorageSync 踩坑实录:别让"顺手一存"变成"隐形炸弹"
微信小程序
用户43242810611412 小时前
小程序埋点设计规范:如何设计可扩展的数据采集体系
微信小程序
m0_526119401 天前
iconfont我修改好颜色,但是在小程序项目是黑色的
小程序
2601_956743681 天前
2026 上海小程序开发甄选:源码、云函数、跨端兼容技术评判
小程序·开发经验·上海
IT_张三1 天前
CSDN-项目分享-暑期备考小程序
小程序
IsJunJianXin1 天前
pdd小程序 cdp 保存响应体
linux·服务器·小程序·pdd小程序·拼多多响应体解密·小程序cdp·拼多多rpc取响应体
Geek_Vison2 天前
APP瘦身实战:从80MB+砍到15MB——基于小程序容器技术剥离APP非核心业务的实践分享
小程序·uni-app·mpaas
weikecms2 天前
聚合返利CPS小程序快速搭建教程
人工智能·微信·小程序
Haibakeji2 天前
长沙餐饮门店点餐配送小程序定制开发
大数据·小程序
2501_915918412 天前
iOS App性能测试工具的实现方法与优化循环指南
android·ios·小程序·https·uni-app·iphone·webview