zoukankan      html  css  js  c++  java
  • 小程序开发中组件通信之自定义事件与Angular的组件交互之监听事件

    小程序(使用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中还有其他办法实现组件通讯,比如使用服务等。

  • 相关阅读:
    博客中添加音乐播放器插件
    博客添加鼠标点击特效
    用好fastboot命令,刷机加锁不用再找工具!
    使用移动终端管理(MDM)轻松进行远程故障排除
    在IT资产生命周期中节省成本的方法:Part 3 维护和支持
    如何做好进程监控?
    OpManager引领智能运维未来的发展方向
    终端安全解决方案如何帮助保护数字化工作空间中的设备
    如何抵御MFA验证攻击
    为什么需要对网络环境进行IP扫描?
  • 原文地址:https://www.cnblogs.com/caiquan/p/10213777.html
Copyright © 2011-2022 走看看