stenciljs 学习五 事件

组件可以使用Event Emitter装饰器发送数据和事件。

Event 定义

参考:
import { Event, EventEmitter } from '@stencil/core';

...
export class TodoList {

  @Event() todoCompleted: EventEmitter;

  todoCompletedHandler(todo: Todo) {
    this.todoCompleted.emit(todo);
  }
}

监听事件(Listen)

可以监听,特定元素的事件

参考:
import { Listen } from '@stencil/core';

...
export class TodoApp {

  @Listen('todoCompleted')
  todoCompletedHandler(event: CustomEvent) {
    console.log('Received the custom todoCompleted event: ', event.detail);
  }
}

监听键盘事件

@Listen('keydown')
handleKeyDown(ev){
  if(ev.keyCode === 40){
    console.log('down arrow pressed')
  }
}

@Listen('keydown.up')
handleUpArrow(ev){
  console.log('will fire when up arrow is pressed');
}

jsx 中使用事件

import { Event, EventEmitter } from '@stencil/core';

...
export class TodoList {

  @Event() todoCompleted: EventEmitter;

  todoCompletedHandler(todo: Todo) {
    this.todoCompleted.emit(todo);
  }
}

<todo-list onTodoCompleted={ev => this.someMethod(ev)}></todo-list>

参考例子

  • 子组件
import { Component,Event,EventEmitter, State} from '@stencil/core';

@Component({
  tag: 'my-child-component',
  styleUrl: 'my-child-component.css',
  shadow: false,
  scoped: false
})

export class MyChildComponent {

  @Event() userClickEvent: EventEmitter;
  UserClickHandler() {
    this.userClickEvent.emit({name:"dalong",age:44});
  }
  @State() name:String="demoapp"
  render(){
    return (
      <div>
        <p onClick={_=>this.UserClickHandler()}>click</p>
        <p>child component</p>
      </div>
    );
  }
}
  • 父组件
import { Component,State, Prop} from '@stencil/core';

@Component({
  tag: 'my-component',
  styleUrl: 'my-component.css',
  shadow: false,
})
export class MyComponent {

  // @Listen("userClickEvent")
  // getUserClickEvent(event: CustomEvent){
  // this.name=JSON.stringify(event.detail)
  // }
  something(event:CustomEvent){
    this.name=JSON.stringify(event.detail)
  }
  @State() name:String="first info"
  @Prop() UserID:String="rong"
  render() {
    return (
      <div >
        <p>{this.UserID}</p>
        <p>{this.name}</p>
        <my-child-component onUserClickEvent={env=>this.something(env)}></my-child-component>
      </div>
    );
  }
}
  • 事件绑定
使用Listen
@Listen("userClickEvent")
  getUserClickEvent(event: CustomEvent){
   this.name=JSON.stringify(event.detail)
}
使用jsx 绑定:
<my-child-component onUserClickEvent={env=>this.something(env)}></my-child-component>
something(event:CustomEvent){
    this.name=JSON.stringify(event.detail)
 }

参考资料

https://stenciljs.com/docs/events

posted on 2018-09-26 23:04  荣锋亮  阅读(619)  评论(0编辑  收藏  举报

导航