随笔 - 122,  文章 - 2,  评论 - 2,  阅读 - 54649

源码地址

https://git.weixin.qq.com/depressiom/my_mp.git

父子组件之间的通信

  • 属性绑定
    • 用于父组件向子组件的指定属性设置数据,仅能设置JSON兼容的数据

属性绑定用于实现父向子传值,而且只能传递普通类型的数据,无法将方法传递给子组件

// <!-- 父组件 -->
/**
 * 页面的初始数据
 */
data: {
    count:0,
    username:'tom',
    name:'JERRY'
},

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

在子组件内部 使用 properties 节点声明对应的属性并使用

   // <!-- 子组件 -->
  /**
   * 组件的属性列表
   */
  properties: {
    count: Number
  }
  <view>父向子属性传值</view>
  <view>组件的count:{{count}}</view>
  • 事件绑定

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

    使用步骤

    • 在父组件的.js中,定义一个函数,这个函数即将通过自定义时间的形式,传递给子组件
    /**
      * 在父组件中定义syncCount 方法
      * 这个方法会被传递给子组件,供子组件进行调用
      */
        syncCount(){
          console.log('syncCount');
        }
    
    • 在父组件的xml中,通过自定义时间的形式,将步骤1中定义的函数引用,传递给子组件
    <!-- 使用bind: 自定义事件名称(推荐:结构清晰) -->
    <my-test count="{{count}}" bind:sync="syncCount"></my-test>
    <!-- 或在 bind 后面直接写上自定义事件名称 -->
    <my-test count="{{count}}" bindsync="syncCount"></my-test>
    
    
    • 在子组件的js中,通过调用this.triggerEvent('自定义事件名称',{/* 参数对象 */}),将数据发送到父组件
      Component({
        properties:{
          count:Number
        },
        methods:{
          addCount(){
            this.setData({
              count:this.properties.count + 1
            })
            this.triggerEvent('sync',{value:this.properties.count})
          }
        }
      })
    
    • 在父组件的JS中,通过e.detail获取到子组件传递过来的数据
      /**
       * 在父组件中定义syncCount 方法
      * 这个方法会被传递给子组件,供子组件进行调用
      */
        syncCount(e){
          console.log('syncCount');
          this.setData({
            count:e.detail.value
          })
        }
    
  • 获取组件实例

    • 父组件还可以通过this.selectComponent() 获取子组件实例对象
    <!-- 使用bind: 自定义事件名称(推荐:结构清晰) -->
    <my-test count="{{count}}" bind:sync="syncCount" class="customA" id="CA"></my-test>
    <!-- 或在 bind 后面直接写上自定义事件名称 -->
    <!-- <my-test count="{{count}}" bindsync="syncCount"></my-test> -->
    <button bindtap="getChild">获取子组件实例</button>
    
    • 这样直接访问子组件的任意数据和方法

可在父组件里调用 this.selectComponent("id或class选择器"), 获取子组件的实例对象,从而直接访问子组件的任意数据和方法。调用时需要传入一个选择器,例如 this.selectComponent(".my-component")

```javascript
  /**
    * 按钮 tap 事件处理函数
    */
    getChild(){
      // 传递 class 或者 id 选择器 CA
      const child = this.selectComponent(".customA")
      // 调用之组件的 setData 方法
      child.setData({
        count:child.properties.count + 1
      })
      // 调用子组件的 addCount 方法
      child.addCount()
    }
```
posted on   depressiom  阅读(72)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示