自定义组件-插槽及父子通信

460 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第8天,点击查看活动详情

小程序学习篇(八),今天一起学习一下小程序中关于自定义组件的插槽的使用吧!相信学完了小程序系列篇,大家都能开发出自己满意的小程序了。

插槽

什么是插槽

在自定义的wxml中,有一个节点,用来承载组件使用者提供的wxml结构。这就是插槽。

单个插槽

默认一个组件只有一个插槽,只允许一个占位。

  1. 封装组件 代码
<view class="wrapper">
    <view>组件内部元素</view>
    <slot></slot>
</view>
  1. 调用组件 代码
<my-component>
    <view>我会被插入到组件的slot中</view>
</my-component>

多个插槽

也给我们提供了一种可以定义多个插槽的方法。设置multipleSlots属性

Component({
    options:{
        multipleSlots: true
    }
})

存在多个插槽的时候,可以用不同的name来区分他们

<view>
    <slot name="before"></slot>
    <slot name="after"></slot>
</view>

自定义组件中-父子组件之间的通信

通信的3种方式:属性绑定,事件绑定,获取子组件实例

  1. 属性绑定 通过属性传递数据,只能设置JSON兼容的数据

传递方向,父向子传递

<my-component count="{{count}}"></my-component>

在子组件中,通过prop接受

properties: {
    count: Number
}
  1. 事件绑定 通过事件绑定的方式,可以传递任意的数据

在子组件的js中,通过调用this.triggerEvent('事件名',{ 参数对象 })

父组件代码

// 推荐bind: 结构更清晰
<my-component count="{{count}}" bind:sync="syncCount"></my-component>
// 或者
<my-component count="{{count}}" bindsync="syncCount"></my-component>

syncCount(){
    console.log('syncCount)
}

子组件代码

<text>count:{{count}}</text>
<button bintap="addCount">+1</button>
addCount(){
    this.setData({
        count: child.properties.count + 1
    })
    this.triggerEvent('getCount',{value: this.data.count})
}

在父组件中,通过e.detail获取传递过来的数据

getCount(e){
    this.setData({
        count: e.detai.value
    })
}
  1. 获取组件实例 父组件可以通过this.selectComponent("id或class选择器")获取子组件的实例对象,可以访问任何的数据和方法,
<my-component count="{{count}}" id="myCom"></my-component>
getComponent(){
    const comp = this.selectComponent('#myCom');
    comp.setData({
        count: child.properties.count + 1
    })
    comp.addCount();
}