微信小程序 - 自定义components组件详解A篇

官网API:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/component.html

 

自定义组件的原因,可以重复使用,只有数据不同且模板一样,节约开发成本.

 

wxml

1 <!--logs.wxml-->
2  <swiper-banner Height="400rpx" Width="100%" imgList="{{banners}}" url="picUrl"></swiper-banner>

js

复制代码
Page({

  /**
   * 页面的初始数据
   */
  data: {
    banners: [], //轮播数组
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getBanners();
  },
  /**
   * 拉取图片
   */
  //获取轮播图片
  getBanners() {
    var self = this;
    wx.request({
      url: 'https://api.it120.cc/jy02149522/banner/list',
      data: {
        type: 0
      },
      success(res) {
        console.log(res);
        if (res.data.code == 0) {
          self.setData({
            banners: res.data.data
          })
        }
      }
    })
  }
})
复制代码

json

{
  "usingComponents": {
    "swiper-banner": "../../components/swiper-banner/index"
  }
}

 

 

 

我们再来看看模板的代码

wxml

复制代码
 1 <view class='swiper'>
 2   <swiper indicator-dots="true" autoplay="true" interval="5000" duration="1000" style="height:{{Height}};width:{{Width}};">
 3     <block wx:for="{{imgList}}" wx:key="*this">
 4       <swiper-item>
 5         <image src="{{item[url]}}" class="slide-image" mode="aspectFill" />
 6       </swiper-item>
 7     </block>
 8   </swiper>
 9 
10   <button bindtap='m'>触发methods里面的方法</button>
11 </view>
复制代码

 

js

复制代码
 1 Component({
 2   // 私有数据
 3   data: {
 4 
 5   },
 6 
 7   // 方法
 8   methods: {
 9     m() {
10       console.log('触发了!');
11     }
12   },
13 
14   // 生命周期函数,可以为函数,或一个在methods段中定义的方法名
15   lifetimes: {
16     attached: function() {
17       console.log('attached');
18     },
19     moved: function() {},
20     detached: function() {},
21   },
22 
23   // 组件所在页面的生命周期函数
24   pageLifetimes: {
25     show: function() {
26       console.log('生命show!');
27     },
28   },
29 
30   // 变量替换以及修改
31   properties: {
32     imgList: {
33       type: Array,
34       value: [],
35       observer: function(newVal, oldVal) {
36         this.setData({
37           imgList: newVal
38         })
39       }
40     },
41     url: {
42       type: String,
43       value: ''
44     },
45     Height: String,
46     Width:String
47   }
48 })
复制代码

 

json

1 {
2   "component": true
3 }

 

wxss

1 .swiper image{
2   width: 100%;
3 }

 

 

 

总结

1. methods里面写方法

2. data初始化变量

3. 但凡变量都和properties脱不了关系

4. 渲染数据应来源于导入组件的页面

5. 被导入的组件必须在json文件定义

{
  "component": true
}

6. 引入组件的页面必须在json文件导入对应的组件路径以及名称

{
  "usingComponents": {
    "swiper-banner": "../../components/swiper-banner/index"
  }
}

 

posted @   Sunsin  阅读(14910)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示