小程序组件封装

雨点打透心脏的1/2处 2022-12-10 07:08 306阅读 0赞

本篇主要带大家从0到有,封装一个自己的w-swiper组件。
具体
详细小程序组件封装,请看https://www.jianshu.com/p/594f0d37feac?from=groupmessage.

创建components目录

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

w-swiper.wxml

  1. <swiper indicator-dots='true' indicator-active-color='#ff5777' autoplay='true' circular='true' interval='3000' class='swiper'>
  2. <block wx:for="{ {images}}" wx:key="index">
  3. <swiper-item>
  4. <image class="swiper-image" src="{ {item.image}}"/>
  5. </swiper-item>
  6. </block>
  7. </swiper>

w-swiper.wxss

  1. .swiper {
  2. height: 360rpx;
  3. }
  4. .swiper-image {
  5. width: 100%;
  6. /* height: 100%; */
  7. }

w-swiper.js

  1. // components/w-swiper/w-swiper.js
  2. Component({
  3. /** * 组件的属性列表 */
  4. properties: {
  5. images:{
  6. type:Array,
  7. value:[]
  8. }
  9. },
  10. /** * 组件的初始数据 */
  11. data: {
  12. },
  13. /** * 组件的方法列表 */
  14. methods: {
  15. }
  16. })

w-swiper.json

  1. {
  2. "component": true,
  3. "usingComponents": { }
  4. }

父组件

在这里插入图片描述

cate.js

  1. // pages/cate/cate.js
  2. Page({
  3. /** * 页面的初始数据 */
  4. data: {
  5. topImages: [],
  6. },
  7. /** * 生命周期函数--监听页面加载 */
  8. onLoad: function (options) {
  9. let that=this;
  10. wx.request({
  11. url: 'http://test.com/api/list', //仅为示例,并非真实的接口地址
  12. data: {
  13. },
  14. method:'get',
  15. header: {
  16. 'content-type': 'application/json' // 默认值
  17. },
  18. success (res) {
  19. console.log(res.data.data.banner.list)
  20. that.setData({ topImages:res.data.data.banner.list})
  21. }
  22. })
  23. },

cate.json

  1. {
  2. "usingComponents": {
  3. "w-swiper":"/components/w-swiper/w-swiper"
  4. },
  5. "navigationBarTitleText": "轮播"
  6. }

cate.wxml

  1. <w-swiper images='{ {topImages}}'></w-swiper>

最终效果:
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,306人围观)

还没有评论,来说两句吧...

相关阅读