小程序组件封装

创建components目录
  1. 在根目录下创建一个components目录,用来存放所有组件。
  2. 例如我们创建一个w-swiper组件,在components目录下创建w-swiper目录。
    自定义组件类似于页面,一个自定义组件由 json wxml wxss js 4个文件组成。

w-swiper.wxml

<swiper indicator-dots='true' 
        indicator-active-color='#ff5777'
        autoplay='true'
        circular='true'
        interval='3000'
        class='swiper'>
  <block wx:for="{{images}}" wx:key="index">
    <swiper-item>
      <image class="swiper-image" src="{{item.image}}"/>
    </swiper-item>
  </block>
</swiper>
w-swiper.wxss
.swiper {
  height: 360rpx;
}

.swiper-image {
  width: 100%;
  /* height: 100%; */
}
w-swiper.js
// components/w-swiper/w-swiper.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    images:{
      type:Array,
      value:[]
    }
  },

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

  },

  /**
   * 组件的方法列表
   */
  methods: {

  }
})

w-swiper.json
{
  "component": true,
  "usingComponents": {}
}
父组件
cate.js
// pages/cate/cate.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
     topImages: [],
  },
 /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that=this;
    
      wx.request({
        url: 'http://test.com/api/list', //仅为示例,并非真实的接口地址
        data: {

        },
        method:'get',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success (res) {
          console.log(res.data.data.banner.list)
          that.setData({topImages:res.data.data.banner.list})
        }
      })
      
  },
cate.json
{
  "usingComponents": {
    "w-swiper":"/components/w-swiper/w-swiper"
  },
  "navigationBarTitleText": "轮播"
}
cate.wxml
<w-swiper images='{{topImages}}'></w-swiper>

最终效果:

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值