官网API:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/component.htmlhtml
自定义组件的缘由,能够重复使用,只有数据不一样且模板同样,节约开发成本.json
wxmlapi
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 }) } } }) } })
jsonxss
{
"usingComponents": {
"swiper-banner": "../../components/swiper-banner/index"
}
}
咱们再来看看模板的代码ide
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>
jsthis
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 })
jsonurl
1 {
2 "component": true 3 }
wxssspa
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"
}
}