我开始了一个项目基于光元素 https://lit-element.polymer-project.org/有许多组件相互嵌套,假设我们有这样的结构:
根组件是my-app
import { LitElement, html, customElement, query } from 'lit-element';
import './my-form';
import './my-view';
import { MyView } from './my-view';
@customElement('my-app')
export class MyApp extends LitElement {
@query('my-view') private myView?: MyView;
private handleCountChange(e: CustomEvent<{ count: number }>) {
if (!this.myView) throw 'my-view not found!';
this.myView.count = e.detail.count;
}
render() {
return html`
<my-form @countChanged=${this.handleCountChange}></my-form>
<my-view></my-view>
`;
}
}
如您所见,我们有两个组件: my-form
import { LitElement, html, customElement, property } from 'lit-element';
@customElement('my-form')
export class MyForm extends LitElement {
@property({ type: Number }) count: any = 0;
private updateCount(e: KeyboardEvent) {
this.count = (<HTMLInputElement>e.target).value;
this.dispatchEvent(
new CustomEvent('countChanged', {
composed: true,
bubbles: true,
cancelable: true,
detail: { count: this.count }
})
);
}
render() {
return html`
<input value=${this.count} @input=${this.updateCount} type="text" />
`;
}
}
和我的观点:
import { LitElement, html, customElement, property } from 'lit-element';
@customElement('my-view')
export class MyView extends LitElement {
@property({ type: Number }) count: number = 0;
render() {
return html`
<p>${this.count}</p>
`;
}
}
为了获得财产count
变化自my-form
into my-view
我调度了事件侦听器然后将其用于my-app
然后在handleCountChange
我正在分配count
价值MyView
除了将其作为组件导入之外,还作为类导入。
目前,这是可行的,但我觉得还有很长的路要走,特别是当我有更多的嵌套组件时。我想知道是否有更好的方法可以做到这一点。
有没有类似的东西Context API
存在于react.js
我想过使用redux
但有人不推荐它与 litElemnt 一起使用。
我正在考虑的想法之一是将事件分派给document
而不是当前的组件,但这也许是一个不好的做法!您有什么建议,请告诉我?