微信小程序封装全局加载动画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 生命周期方法中使用。

相关推荐
咖啡八杯7 小时前
微信小程序人脸认证1.0迁移2.0
后端·微信小程序
xshirleyl7 小时前
微信小程序开发week8-慕尚花坊项目
微信小程序·小程序
admin and root9 小时前
Claude+Trae大模型 配置Chrome MCP联动Yakit自动化渗透测试
微信小程序·渗透测试·自动化·攻防演练·ai安全·claude code·ai自动化渗透测试
code_li1 天前
小程序上线需要的资质证书汇总
小程序·上线·发布·资质
hnxaoli1 天前
统信小程序(十三)循环键鼠操作程序
python·小程序
i查拉图斯特拉如是1 天前
使用workbuddy 30分钟搭建微信小程序
微信小程序·小程序
IceSugarJJ1 天前
Open-AutoGLM项目学习
语言模型·微信小程序·github
2501_916008891 天前
Mac 上生成 AppStoreInfo.plist 文件,App Store 上架
android·macos·ios·小程序·uni-app·iphone·webview
咖啡の猫1 天前
小程序协同工作和发布
小程序
维双云1 天前
小程序怎么制作工具?与其盲目找开发,不如先分清自己要哪一种
小程序