微信小程序父子组件通信详解

1 父组件向子组件传递数据:

1.1 在父组件的文件夹中的.json文件下引入子组件

{
  "usingComponents": {
  	//"Tab" 是自己定义的组件名称
  	//"../../components/Tab/Tab" 是组件的路径
    "Tab":"../../components/Tab/Tab"
  }
}

1.2 在父组件里以标签的形式写入子组件

如果需要传值的话,在标签上自定义属性名,属性值要以双花括号保住

<Tab tabs="{{tabs}}"/>

子组件是通过properties来获取父组件传递的数据,接着子组件把这个数据当成是data中的数据使用即可

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    tabs:{
      type:Array, //要接收的数据类型
      value:[] //默认值(可选)
    }
  }
})

2 子组件向父组件传递数据:

子组件中监听方法:

<button size="mini" bind:tap="handleTap">+1</button>
``
子组件中发送事件:

```javascript
methods: {
    handleTap(){
      //三个参数:方法名称,数据,选项
      this.triggerEvent("increment",{index:0})
    }
  }

父组件页面中使用bind监听该方法:

<Tab tabs="{{tabs}}" 
     bind:increment="handleIncrement">
</Tab>

父组件方法使用:

handleIncrement(e){
	//e.detail中就是子组件传递的数据
    this.setData({
      count:this.data.count +1
    })
  }

猜你喜欢

转载自blog.csdn.net/weixin_43950643/article/details/107676563
今日推荐