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

相关推荐
白臻2 分钟前
小程序 npm 支持
前端·小程序·npm
guanpinkeji2 小时前
剧本杀小程序:助力商家发展,提高游戏体验
游戏·小程序·游戏开发·小程序开发·剧本杀·剧本杀小程序
酷爱码4 小时前
新闻电影资讯类小程序模板源码
小程序
Conan_Ritchie4 小时前
微信小程序简历Demo
微信小程序·小程序
酷爱码7 小时前
旅游计划定制小程序网页模板源码
小程序·旅游
努力学习的木子13 小时前
uniapp如何隐藏默认的页面头部导航栏,uniapp开发小程序如何隐藏默认的页面头部导航栏
前端·小程序·uni-app
guanpinkeji19 小时前
家政小程序的开发,带动市场快速发展,提高家政服务质量
小程序·小程序开发·家政·家政小程序·家政服务小程序
Cc_Debugger19 小时前
微信小程序消息通知(一次订阅)
微信小程序·小程序
joan_851 天前
微信小程序利用第三方库xlsx导出excel
微信小程序·excel
栗豆包1 天前
【计算机毕业设计】020基于weixin小程序订餐系统
小程序·课程设计