//自定義組件component.json
{
"component": true
}
//引用自定義組件的頁面 page.json
{
"usingComponents": {
"component-tag-name": "../component/component"
}
}
|
<!-- 這是自定義組件的內(nèi)部WXML結(jié)構(gòu)(component.wxml)-->
<view class='wapper'>
<text>this is component</text>
<slot name="slot1"></slot>
我在中間
<slot name="slot2"></slot>
</view>
<!-- 以下是對一個自定義組件的引用 (page.wxml)-->
<view>
<text>This is Page</text>
<component-tag-name inner-text="Some text" class="page-component">
<view slot="slot1" class="slot">來自page頁面,通過slot標(biāo)簽</view>
<view slot="slot2"></view>
</component-tag-name>
</view>
|
//component.wxss
.wapper{
background-color:#ccc;
width: 100%;
height:auto;
}
.slot{
color:red;
}
//page.wxss
.page-component{
color:#fff;//有效,繼承樣式
padding:10px;//無效
}
.slot{
color:green;
}
|
//component.js
Component({
options: {
multipleSlots: true // 在組件定義時的選項中啟用多slot支持
},
properties: {
// 這里定義了innerText屬性,屬性值可以在組件使用時指定
innerText: {
type: String,
value: 'default value', //不存在此屬性時
}
},
data: {
// 這里是一些組件內(nèi)部數(shù)據(jù)
someData: {}
},
methods: {
// 這里是一個自定義方法
customMethod: function(){}
}
})
|

通過上面的代碼和顯示結(jié)果可以看出:
Tip:page代指引用組件頁面,component代指自定義組件
<!-- page.wxml --> <component-tag-name fromPage="來自Page" data-other="from dataset"></component-tag-name> |
Component({
properties: {
formPage: String //簡寫
/*
myProperty: { // 屬性名
type: String, // 類型(必填),目前接受的類型包括:String, Number, Boolean, Object, Array, null(表示任意類型)
value: '', // 屬性初始值(可選),如果未指定則會根據(jù)類型選擇一個
observer: function(newVal, oldVal){} // 屬性被改變時執(zhí)行的函數(shù)(可選),也可以寫成在methods段中定義的方法名字符串, 如:'_propertyChange'
}
*/
},
attached:function(){
console.log(this.properties.fromPage);
console.log(this.data.fromPage); //用data也能訪問properties
//設(shè)置properties值用setData()
this.setData({
fromPage: '改變了'
});
console.log(this.properties.fromPage);
//通過dataset獲取data-other的值
console.log(this.dataset.other);
}
})
|
參考文檔:微信小程序-自定義組件