微信小程序骨架屏

453 阅读1分钟

文档: developers.weixin.qq.com/miniprogram…

页面完成之后, 生成骨架屏并配置

(1) 生成骨架屏 点击下图中按钮生成骨架屏代码(同目录下的xxx.skeleton.wxml和xxx.skeleton.wxss)

(2) 引入到页面并配置

  • import标签引入
  • template标签使用
  • template标签的data属性和下面元素的data-skeleton-hide和hidden控制即可(即接口响应后修改以上属性绑定的变量,使得骨架屏隐藏,真正内容出现)
  • wxss中@import引入骨架屏css
  • wxml页面布局.为了使真实数据的位置与骨架屏一致,此时应使用 absolute 方式定位页面主模块 my.wxml
<import src="my.skeleton.wxml" />
<template is="skeleton" wx:if="{{loading}}" data="{{hideSwiper, hideList}}"></template>

<view class="wrapper">
  <view class="my-swiper" data-skeleton-hide="hideSwiper" hidden="{{!hideSwiper}}">
    <swiper indicator-dots="{{indicatorDots}}"
        autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}">
        <block wx:for="{{background}}" wx:key="*this">
          <swiper-item>
            <view class="swiper-item {{item}}">{{item}}</view>
          </swiper-item>
        </block>
      </swiper>
  </view>

  <view class="list" data-skeleton-hide="hideList" hidden="{{!hideList}}">
    <view class="item" wx:for="{{list}}" wx:key="index">
      <text style="font-size: 100rpx; color: red;">{{item}}</text>
    </view>
  </view>
</view>

my.wxss

// my/my.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    background: [],
    indicatorDots: true,
    vertical: false,
    autoplay: false,
    interval: 2000,
    duration: 500,
    list: [],
    loading: true,
    hideList: false,
    hideSwiper: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.loadData();
  },

  loadData() {
    setTimeout(() => {
      this.setData({
        background: ['demo-text-1', 'demo-text-2', 'demo-text-3'],
        hideSwiper: true
      });
    }, 1000);
    setTimeout(() => {
      this.setData({
        list: [1,2,3,4,5,6,7,8,9,0],
        loading: false,
        hideList: true
      });
    }, 2000);
  }
})

my.wxss

@import "my.skeleton.wxss";
/* my/my.wxss */
.swiper-item {
  width: 100%;
  height: 100%;
}
.demo-text-1 {
  background: blue;
}
.demo-text-2 {
  background: red;
}
.demo-text-3 {
  background: pink;
}

.wrapper {
  width: 750rpx;
  height: auto;
}
.wrapper .my-swiper {
  width: 100%;
  height: 300rpx;
  position: absolute;
  left: 0;
  top: 0;
}
.wrapper .list {
  width: 100%;
  height: 800rpx;
  overflow: auto;
  position: absolute;
  left: 0;
  top: 300rpx;
}