美文网首页
8.组件间的通信

8.组件间的通信

作者: LucXion | 来源:发表于2023-10-23 10:02 被阅读0次
    父组件 接收 子组件 的传值

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

    // 子组件 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()
            }
        }
    

    相关文章

      网友评论

          本文标题:8.组件间的通信

          本文链接:https://www.haomeiwen.com/subject/zcadidtx.html