目錄
前言
在微信小程序開發的過程中,我認爲組件式開發是必須要掌握的一種技能。開發者可以將頁面內的功能模塊抽象成自定義組件,以便在不同的頁面中重複使用。也可以將複雜的頁面拆分成多個低耦合的模塊,有助於代碼維護。自定義組件在使用時與基礎組件非常相似。
組件新建
1、首先在根目錄下創建一個components目錄,用來存放所有組件。
2、然後右擊components文件夾選擇新建一個components。
3、這裏我們輸入myTabBar就會給我們自動創建一個組件,裏面包含了 json wxml wxss js 4個文件。
4、要編寫一個自定義組件,首先需要在 json 文件中進行自定義組件聲明(將 component 字段設爲 true 可這一組文件設爲自定義組件)。
{
"component": true,
"usingComponents": {}
}
組件編寫
到這裏組件就新建成功,父組件通過屬性傳值在子組件的properties屬性可以取到,但是必須定義好type類型。子組件也可以通過triggerEvent事件把值傳給父組件。下面我們給大家展示一下組件的代碼。
1、wmxl代碼
<scroll-view scroll-x='true'>
<view style="width:{{width}}" class="tabBarBox">
<view data-item="{{item}}" bindtap="tabBarItemTap" class="{{selected_tabBar.name==item.name?'tabBarItemActive':'tabBarItem'}}" wx:for="{{data_tabBar_list}}" wx:for-index="idx" wx:for-item="item" >
<text>{{item.name}}</text>
</view>
</view>
</scroll-view>
2、js代碼
Component({
properties: {
data_tabBar_list: {
type: Array,
value: ''
},
selected_tabBar: {
type: Object,
value: {}
},
width: {
type: String,
value: '600px'
},
},
data: {},
methods: {
tabBarItemTap:function(e){
let data = e.currentTarget.dataset.item;
this.triggerEvent("tabBarItemTap", data);
}
}
})
3、wxss代碼
.tabBarBox{
padding: 8px;
display: flex;
flex-direction: row;
width:600px;
}
.tabBarItem{
height: 20px;
color: #B4B4B4;
display: inline-block;
margin-right:18px;
}
.tabBarItemActive{
height: 20px;
margin-right:18px;
display: inline-block;
}
組件調用
在json文件中使用usingComponents引用組件
{
"usingComponents": {
"myLoading": "/components/myLoading/index",
"myMessageBox": "/components/myMessageBox/index",
"myTabBar": "/components/myTabBar/index"
}
}
在父頁面以標籤的形式就可以調用
<myTabBar width="{{'600px'}}" bind:tabBarItemTap="tabBarItemTap" data_tabBar_list="{{data_tabBar_list}}" selected_tabBar="{{selected_tabBar}}"></myTabBar>