微信小程序的自定义组件用多了就会上瘾,恨不得把页面都写成组件,但是这样就会设计很多组件间的通信问题,那就总结一下,在微信小程序里,组件间是如何通信传值的。
父组件给子组件传值
子组件需要接收父组件传过来的值,在properties里定义:
/** * 组件的属性列表 */ properties: { //图片地址 img_src: { type: String }, //可视区域的大小 view_width: { type: String }, view_height: { type: String }, setX: { type: String }, setY: { type: String }, setScale: { type: String } },父组件需要传值给子组件,直接写在子组件的内容里就行:
zoomImgByView id='mapLayout' img_src="{{img_list[index].image_url}}" view_width="{{img_list[index].width}}" view_height="{{img_list[index].height}}" /这样,就可以把父组件的信息传给子组件了。
子组件给父组件传值,会麻烦一点。
子组件通过事件传值,绑定一个事件 close:
view class='iosTip-close' bindtap='close'/view事件close需要写上triggerEvent:
close: function() { var myShow = { myShow: false } this.triggerEvent('myevent', myShow) //myevent自定义名称事件,父组件中使用 }父组件中引入子组件,并在子组件中写上 bind:myevent:
iosTip bind:myevent="onGetShow" wx:if="{{IsIosShow}}" /父组件的即可通过onGetShow拿到子组件传过来的值:
onGetShow: function (e) { console.log(e.detail.myShow) this.setData({ IsIosShow: e.detail.myShow }) },













