美文网首页
组件和页面通信

组件和页面通信

作者: 晓函 | 来源:发表于2020-12-03 12:02 被阅读0次

    父传子很简单:

    【组件】

    #mycomponent.js
    Component({
      properties: {
        title:String
      },
      lifetimes:{
        attached:function(){
          console.log(this.data.title);
        }
      }
    
    })
    

    【页面】

    #index.wxml
      <my-component title="我很好">
      </my-component>
    

    子传父:
    要使用triggerEvent,类似win32里面的sendMessage消息
    【组件】

    #mycomponent.wxml
    <button bindtap="OnTap">保存地址</button>
    
    #mycomponent.js
    Component({
      methods:{
        onTap(e){
          //发送地址改变的通知
          this.triggerEvent("addrChange","中国深圳");
        }
      }
    
    })
    

    【页面】

    #index.wxml
    <view>{{address}}</view>
    <my-component bind:addrChange="showAddress"></my-component>
    
    
    #index.js
    showAddress(e){
      setData({address:e.detail});
    }
    

    相关文章

      网友评论

          本文标题:组件和页面通信

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