目录
1 使用自定义组件:
1 创建一个文件夹,在其中新建Component
自动生成四个文件
2 在你要使用自定义组件的 json文件配置自定义组件;
前面是自定义的组件名称;后面是以绝对路径找到自定义组件
3 就可以在wxml中 使用<demo></demo>自定义组件了
2 组件通信
1 父组件(页面)向子组件通信
通过传递属性数据的方式,子组件在properties中接收
父wxml: 通过属性传递数据
<demo color="red" num="100"></demo>
子js: 在properties中接收
Component({ /** * 组件的属性列表 */ properties: { color: { type: String, value: '' }, num: { type: Number, value: '', observer() { console.log(this, arguments); } } } }
子组件wxml中 可以使用
<view>父传过来的num: {{num}}</view> <view>父传过来的color: {{color}}</view>
2 子组件向父组件(页面)通信
通过自定义事件:(观察者模式)
让父组件订阅自定义事件,通过bind绑定自定义事件名(这里事件名叫 Father)
<demo bindFather="receiveMassage"></demo>
在子组件中通过triggerEvent方法,来发布自定义事件,并且传递数据,若传多条数据,放在一个数组中传递。
<button bindtap="sendMsg">点击传参</button>
methods: { sendMsg() { this.triggerEvent('Father', [100, 'abc', true]); } }
在父组件中,定义事件回调函数,通过事件对象中的e.detail来接收数据
receiveMassage(e) { console.log(e); this.setData({ num: e.detail[0], str: e.detail[1], bollean: e.detail[2], }) },
执行顺序是:点击button按钮 触发了sendMsg, sendMsg中发布了Father消息,demo监听Father,所以触发receiveMassage,传递是数据在其事件对象中。
3 兄弟间的通信
子传递数据到父, 父在传给子
3 插槽
1 在你要使用自定义组件的 json文件配置自定义组件;
test.json
{ "usingComponents": { "chacao": "/components/chacao/chacao" } }
2, 在组件的脚本文件中传递options配置属性,传递multipleSlots: true属性
chacao.json
Component({ options: { multipleSlots: true } }
3 使用插槽
text.wxml
<!-- 插槽 --> <chacao> <view slot="header">a</view> <view slot="header">b</view> <view slot="header">c</view> <view>d</view> <view slot="body">e</view> <view slot="header">f</view> <view slot="body">g</view> </chacao>
<view>插槽中的一般组件</view> <slot name="header"></slot> <view>插槽中的一般组件</view> <slot name="body"></slot> <slot></slot> <view>插槽中的一般组件</view>
执行过程: