LitElement
一个简单的基类,用于使用 lit-html 创建快速,轻量级的 Web 组件。
文献资料
完整文档可在 lit-element.polymer-project.org 中找到。
总览
LitElement 使用 lit-html 渲染到元素的 Shadow DOM 中,并添加了 API 以帮助管理元素的属性和属性。 LitElement 对属性更改做出反应,并使用 lit-html 进行声明式渲染。 有关如何为 lit-element 创建模板的其他信息,请参见 lit-html 指南。
import {LitElement, html, css, customElement, property} from 'lit-element'; // This decorator defines the element. @customElement('my-element') export class MyElement extends LitElement { // This decorator creates a property accessor that triggers rendering and // an observed attribute. @property() mood = 'great'; static styles = css` span { color: green; }`; // Render element DOM by returning a `lit-html` template. render() { return html`Web Components are <span>${this.mood}</span>!`; } } <my-element mood="awesome"></my-element>
注意,此示例使用装饰器创建属性。 装饰器是当前在 TypeScript 或 Babel 中可用的提议标准。 LitElement 还支持声明反应特性的 vanilla JavaScript 方法。
示例
- Runs in all supported browsers: Glitch
- Runs in browsers with JavaScript Modules: Stackblitz, JSFiddle, JSBin, CodePen.
- You can also copy this HTML file into a local file and run it in any browser that supports JavaScript Modules.
安装
从项目文件夹中运行
$ npm install lit-element
安装旧浏览器所需的 web 组件 polyfills
$ npm i -D @webcomponents/webcomponentsjs
受支持的浏览器
支持所有现代浏览器的最后两个版本,包括Chrome、Safari、Opera、Firefox和Edge。此外,还支持Internet Explorer 11。
Edge和Internet Explorer 11需要 web 组件 polyfills。
贡献
请查看 CONTRIBUTING.md。