小程序(使用triggerEvent实现)
【https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/events.html】
- 监听事件
<!-- 当自定义组件触发“myevent”事件时,调用“onMyEvent”方法 -->
<component-tag-name bindmyevent="onMyEvent" />
<!-- 或者可以写成 -->
<component-tag-name bind:myevent="onMyEvent" />
Page({ onMyEvent(e) { e.detail // 自定义组件触发事件时提供的detail对象 } })
- 触发事件
自定义组件触发事件,需要使用 triggerEvent
方法,指定事件名、detail对象和事件选项:
<!-- 在自定义组件中 --> <button bindtap="onTap">点击这个按钮将触发“myevent”事件</button>
Component({ properties: {}, methods: { onTap() { const myEventDetail = {} // detail对象,提供给事件监听函数 const myEventOption = {} // 触发事件的选项 this.triggerEvent('myevent', myEventDetail, myEventOption) } } })
Angular(使用EventEmitter实现)(父组件监听子组件的事件)
【https://angular.cn/guide/component-interaction】
import { Component, EventEmitter, Input, Output } from '@angular/core'; @Component({ selector: 'app-voter', template: ` <h4>{{name}}</h4> <button (click)="vote(true)" [disabled]="didVote">Agree</button> <button (click)="vote(false)" [disabled]="didVote">Disagree</button> ` }) export class VoterComponent { @Input() name: string; @Output() voted = new EventEmitter<boolean>(); didVote = false; vote(agreed: boolean) { this.voted.emit(agreed); this.didVote = true; } }
import { Component } from '@angular/core'; @Component({ selector: 'app-vote-taker', template: ` <h2>Should mankind colonize the Universe?</h2> <h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3> <app-voter *ngFor="let voter of voters" [name]="voter" (voted)="onVoted($event)"> </app-voter> ` }) export class VoteTakerComponent { agreed = 0; disagreed = 0; voters = ['Mr. IQ', 'Ms. Universe', 'Bombasto']; onVoted(agreed: boolean) { agreed ? this.agreed++ : this.disagreed++; } }
当然了,angular中还有其他办法实现组件通讯,比如使用服务等。