微信小程序 组件通信 插槽

目录

1 使用自定义组件:

2 组件通信

1 父组件(页面)向子组件通信

2 子组件向父组件(页面)通信

3 兄弟间的通信

3 插槽


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>

执行过程:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值