官網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"
}
}