微信小程序的组件通信

属性绑定

用于父组件向子组件的指定属性设置数据,仅能设置json兼容的数据
子组件
wxml:

<view>子组件的count值:{{count}}</view>

js

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    count: Number
  }
  )}

父组件
wxml:

<test2 count="{{count}}"></test2>
<view>父组件的count值:{{count}}</view>

js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    count: 1
  }
  )}

json

{
  "usingComponents": {
    "test2":"/components/test2/test2"
  }
}
效果示例

在这里插入图片描述

事件绑定

用于子组件向父组件传递数据,可以传递任意数据
步骤:

  1. 在父组件的js中,定义一个函数,这个函数即将通过自定义事件的形式传递给子组件
  2. 在父组件wxml中,通过自定义事件的新年形式,将步骤1中定义的函数引用,传递个子组件
  3. 在子组件的js中,通过this.triggerEvent(‘自定义事件名称’,{参数对象}),将数据发送到父组件
  4. 在父组件的js中,通过e.detail获取到子组件传递过来的数据

子组件wxml:

<view>子组件的count值:{{count}}</view>
<button type="primary" bindtap="addCount">子组件的按钮:count+1</button>

子组件js

// components/test2.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    count: Number
  },
  /**
   * 组件的初始数据
   */
  data: {
  },
  /**
   * 组件的方法列表
   */
  methods: {
    addCount() {
      this.setData({
        count: this.properties.count + 1
      })
      //触发事件,发送数据给父组件
      this.triggerEvent("eventHandler",{value:this.properties.count})
    }
  }
})

父组件绑定事件 事件名称eventHandler 数据接收函数addCount

<test2 count="{{count}}" bind:eventHandler="addCount"></test2>
<view>父组件的count值:{{count}}</view>
效果示例

在这里插入图片描述

获取组件实例

父组件通过this.selectComponent('class或id选择器')获取子组件实例的对象,这样可以直接访问子组件的任意数据和方法`

父组件

wxml:

<test2 count="{{count}}" bind:eventHandler="addCount" id="Child"></test2>
<view>父组件的count值:{{count}}</view>
<button type="primary" bindtap="getChild">获取子组件实例对象</button>

父组件js

  getChild() {
    const child = this.selectComponent("#Child")
    child.setData({
      count:child.properties.count+1//修改子组件的数据
    })
    //child.addCount()调用子组件的函数
  },
子组件

wxml

<view>子组件的count值:{{count}}</view>
<button type="primary" bindtap="addCount">子组件的按钮:count+1</button>

js

  methods: {
    addCount() {
      this.setData({
        count: this.properties.count + 1
      })
      //触发事件,发送数据给父组件
      this.triggerEvent("eventHandler",{value:this.properties.count})
    }
  }

效果示例
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值