小程序中父子组件通信的方法

引入组件

  • 全局组件

    在app.json文件中配置usingComponents,多个组件用逗号隔开,最后一个不加逗号

  • 单页面使用的组件

    在页面的.json文件中配置usingComponents

    "usingComponents": {
          
          
    	"myConponent": "./xxx/xxx"
    }
    

    配置好后即可在页面中使用组件

    <myConponent></myConponent>
    

    注:组件名可以是小驼峰写法,也可以是短横线分隔符写法,json文件中引入自定义组件时,驼峰命名无法自动转换成 - 形式。所以组件名在定义、注册、引用时必须统一,<myConponent></myConponent><my-conponent></my-conponent>对应的是不同组件。

一、父组件向子组件传递数据:WXML 数据绑定

在子组件 properties 中可以注册一些自定义组件属性,父组件调用子组件时可以向 properties 中的自定义属性传值。

Component({
    
    
    properties: {
    
    
        personObj: {
    
    
            type: Object,//定义传入属性值的类型
            value: {
    
    },//定义默认属性值
        }
    },
    data: {
    
    
        number:1
    },
})

假如父组件中有数据:

data: {
    
    
    person:{
    
    
        name:"sun",
        age:10
    }
},

父组件调用子组件时可以给子组件properties中的属性传值

<childDemo personObj="{
     
     {person}}"></childDemo>

子组件中可以像使用自身属性一样使用接收的属性值

<view>我是子组件内容</view>
<view>{
   
   {personObj.name}}</view>
<view>{
   
   {personObj.age}}</view>

注:这样的数据绑定只能传递 JSON 兼容数据。

二、子组件向父组件传递数据:事件绑定triggerEvent()

子组件通过this.triggerEvent()方法提交一个可以被父组件监听的事件

父组件的页面可以监听子组件事件,并从子组件获取数据。子组件也通过这种方式触发父组件的方法。

子组件wxml代码

<button bindtap="onTap">点击这个按钮将触发父组件“myevent”事件</button>

子组件js代码

onTap: function(){
    
    
    var myEventDetail = {
    
    
        valueA: 1,
        valueBB: 2
    } // detail对象,包含需传递给父组件的数据,提供给事件监听函数,可选参数
    var myEventOption = {
    
    } // 触发事件的选项,可选参数。
    this.triggerEvent('myevent', myEventDetail, myEventOption)
},

父组件wxml代码

<childDemo bind:myevent="myeventListener"></childDemo>

父组件js代码

myeventListener: function (recivedEvent) {
    
    
    console.log(recivedEvent)
    console.log(recivedEvent.detail);//{valueA: 1, valueBB: 2}
},

三、父组件访问子组件数据:selectComponent()

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

假如子组件 childDemo 有如下数据和方法

data: {
    
    
    number:1
},
methods: {
    
    
    log: function () {
    
    
        console.log("子组件方法");
    }
}

在父组件引用子组件

<childDemo id="childDemo"></childDemo>

父组件js代码:

handleTap: function () {
    
    
    let childObj = this.selectComponent('#childDemo')//获取子组件实例对象
    console.log(childObj.data.number);//访问子组件实例属性
    this.selectComponent('#childDemo').log()//访问子组件实例方法
},

四、用< slot >向子组件插入内容

在组件模板中可以提供一个 <slot> 节点,用于承载组件引用时提供的子节点。

子组件模板:

<view class="wrapper">
  <view>这里是组件的内部节点</view>
  <slot></slot>
</view>

父组件模板

<view>
  <component-tag-name>
    <!-- 这部分内容(整个标签)将被放置在组件 <slot> 的位置上 -->
    <view>这里是插入到组件 slot 中的内容</view>
  </component-tag-name>
</view>

猜你喜欢

转载自blog.csdn.net/weixin_44001906/article/details/125748890