组件定义流程
1)为了方便管理组件文件,创建一个目录来存放组件(可省略该步骤)
组件与页面都有相同的配置,包括的文件有:wxml、wxss、js、json 四个文件。
2)编写组件
编写组件与编写页面一样,没有什么区别。
3)引入组件
哪个页面需要用到组件,就要在哪个页面下的 json 文件中配置以下信息:
{
"usingComponents": {
"event-item": "../../components/event-item/event-item"
}
}
usingComponents
字段下包含了多个组件的配置信息,包括组件名称(可自定义)、组件路径(组件的相对路径)。组件名称可以与组件的文件名不同,在 wxml 使用组件时以配置的组件名称为主。
4)使用组件
<view class="index">
<event-item></event-item>
</view>
灵活的组件
slot
slot 允许在使用组件时插入更多的内容。简单来讲,就是在组件内预设一个位置,使用组件时插入更多的内容到组件内。这些附加的内容位置取决于 slot 在组件内的预设位置。实际上,slot 就是组件的内容占位符。
使用流程
1)在组件中添加 slot 标签,预设后期使用组件时内容显示在组件的具体位置
<view class="event-items">
<view>hell world</view>
<!-- slot -->
<slot></slot>
</view>
2)使用组件时,在组件中插入附加的内容
<view class="index">
<event-item>
<view>more node</view>
<view>do you have a nice day?</view>
<view>
you say:
<view>yes of course!</view>
</view>
</event-item>
</view>
properties
为了使组件更加灵活,实现组件可配置,properties
非常重要。properties 与 Vue 中的 Props 概念相同,properties 可以作为组件的参数接收外部传递进来的值。
使用流程
1)在组件 JS 文件中,Component 内添加 properties 字段。properties 是一个字典,可以接收许多值
Component({
properties: {
itemType,
eventItems
}
}
2)给每一个 properties 字段添加一个 type 属性,指定数据类型
Component({
properties: {
itemType: {
type: String
},
eventItems: {
type: Array
}
}
}
3)可以给 properties 字段添加一个 value 属性,指定默认值(可省略该步骤)
Component({
properties: {
itemType: {
type: String,
value: 'primary'
},
eventItems: {
type: Array
}
}
}
4)注意事项:字段名称必须采用驼峰命名法,组件传递值时必须采用短横线命名法,也就是说 itemType 对应 item-type。
5)使用组件,传递值
<view class="index">
<event-item item-type="{{'wait'}}" event-items="{{['one', 'two', 'three']}}"></event-item>
</view>
传递值可以控制组件内部发生不一样的变化,实现组件的灵活配置。