8.组件间的通信

2023-10-23  本文已影响0人  LucXion
父组件 接收 子组件 的传值

由子组件主动发送通知的形式来传值,父组件通过绑定来接收子组件通知。

// 子组件 js 中
/**
*  在合适的方法内,发送通知向父组件传值
*  发送的数据结构为一对 key , value
*  key:通知名称  value:值
*/ 
    this.triggerEvent(
        'change',selIndex
    )

// 父组件,在wxml中给通知绑定方法
/**
*  有两种方式 bind:change / bindChange
*  .js 中实现 receiveChangeSelIndex 
*/ 
<headerTab bind:change="receiveChangeSelIndex"></headerTab>

// 父组件,.js 中接收通知对象,默认字段 detail
  receiveChangeSelIndex(notification) {
      // 新语法
      const { detail } = notification
      this.setData ({
        titleindex:detail
      })
  }
父组件传值到子组件

子组件中相互之间没有绑定关系,必须通过相同的父组件作为中间人传值


// 子组件 .js中,在 property 中声明接收的属性
/**
* 组件的属性列表
*/
    properties: {
        tag:String
    }

// 将子组件中的属性与父组件中的属性进行绑定
<list tag = "{{titleindex}}"></list>

// 给属性添加观察者,值发生改变时触发,通过 observers 关键字
/**
*  默认接收新值
*  changeType 是方法,在methods中实现,调用时加 this
*/
    observers :{
        tag:function(newValue){
            this.changeType()
        }
    }
上一篇下一篇

猜你喜欢

热点阅读