第一步:创建子组件目录,可以与根目录同级别,在目录下面创建对应的wxml,wxss,js以及json文件;
第二部:wxml,wxss按照正常的组件方式编写即可,如view,text标签都可以使用;
第三部:重点来了,json文件需要开启声明自定义组件,component与usingComponents同级
{
"component": true,
"usingComponents": {
}
}
第四部:编写js,以Component组件方式编写,类似vue子组件,里面可以有父组件的参数properties对象,组件的属性data,组件方法methods
另外还可以以插槽的方式定义多个slot,通过name区分。其中properties内可以定义属性,需要初始化属性类型和初始值。
第五步:最后,我们就可以在父组件内调用了,需要在父组件的json文件的usingComponents内调用,然后在wxml里直接引用,传参即可。
以上文字代码纯手工,多多点赞转发加收藏★
附完整子组件父组件代码:
子组件children.js
Component({
/**
* 组件的属性列表
*/
properties: {
name: {
type: String,
value: ''
},
list: {
type: Object,
value: Object
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
}
})
子组件children.wxml
<view>
我是子组件
插槽1
<slot name="fitst"></slot>
插槽2
<slot name="second"></slot>
插槽3
<slot name="three"></slot>
</view>
子组件children.json
{
"component": true,
"usingComponents": {
}
}
父组件parent.json
{
"navigationBarTitleText": "",
"enablePullDownRefresh": true,
"onReachBottomDistance": ,
"usingComponents": {
"children": "../children"
}
}
父组件parent.wxml
<view>
<children name="自定义组件测试">
我是父组件
<view slot="fitst">我是插槽1</view>
<view slot="second">我是插槽2</view>
<view slot="three">我是插槽3</view>
</children>
</view>