💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 组件间通信与事件 ### 组件间通信 组件间的基本通信方式有以下几种。 #### 1.WXML 数据绑定:用于父组件向子组件的指定属性设置数据,仅能设置 JSON 兼容数据。 ``` <view> <component-tag-name prop-a="{{dataFieldA}}" prop-b="{{dataFieldB}}"> </component-tag-name> </view> ``` #### 2.事件:用于子组件向父组件传递数据,可以传递任意数据。 事件分为冒泡和非冒泡事件。 ![](https://box.kancloud.cn/0f87eed2f3d1c84d0d74437220fdc8f6_1014x598.png) ![](https://box.kancloud.cn/e43f3448c53ca7af486351ed2398d805_1016x358.png) index.wxml ``` <like isLike="{{classic.like_status}}" count="{{classic.fav_nums}}" bind:like="onLike"></like> ``` >使用bind為like組件綁定事件名為like的事件 index.js ``` Page({ onLoad() { wx.request({ url: 'http://bl.7yue.pro/v1/classic/latest', header: { 'Content-Type': 'application/json', "appkey": "9xK0CrzQREI1yGPh" }, success: res => { this.setData({ classic: res.data }) } }) }, onLike(e){ console.log(e.detail) } }) ``` like.wxml ``` <view> <image src="{{isLike?yesSrc:noSrc}}" catchtap="onLike"></image> <text>{{count}}</text> </view> ``` like.js ``` Component({ properties: { isLike:{ type:Boolean, value:false }, count:{ type:Number, value:0 } }, data: { yesSrc:"/images/like.png", noSrc:"/images/unlike.png" }, methods: { onLike(){ var isLike = this.properties.isLike; var count = this.properties.count; count = isLike?count-1:count+1; this.setData({ isLike:!isLike, count:count }) // 子组件自定义事件向父组件传递 传递事件名称和参数 let behavior = this.properties.isLike?"like":"like/cancel"; this.triggerEvent("like",{behavior:behavior}) } } }) ``` >triggerEvent 方法可以包含三个参数,分别是事件名、detail 对象、事件选项 在获取到 dataset 中的参数之后,可以当做 detail 对象传给父组件 ![](https://box.kancloud.cn/a6ef65a1203ab5d1e6e563a79a6a29ef_457x68.png) 关于 triggerEvent 的第三个参数“事件选项”,可以参考这个表格:![](https://box.kancloud.cn/5f63bfcc699e10a369237124367062e4_963x225.png) #### 3.父组件通过 this.selectComponent 方法获取子组件实例对象,可以直接访问组件的任意数据和方法。