轻量级的JavaScript 框架——Lit

1383

Lit 是一个快速、轻量级、反应式的框架,用于构建 Web 组件。与其它框架相比,Lit 并没有那么出名。它是建立在Web组件标准之上,优先考虑了速度和一小部分有用的功能。

如何使用Lit来构建Web组件

Lit项目的构建方法有很多种,这里我们先介绍一个入门到方法,使用npm来安装 Git 和 Node.js ( ) 的命令行。

转到命令行并键入git clone https://github.com/lit/lit-element-starter-js.git. 此命令将一个简单的示例项目部署到lit-element-starter-js目录中。cd进入该目录并使用npm install.

现在可以使用npm run serve. 如果您访问localhost:8000,就会发现应用程序正以下图运行。

Listing 1. Reactivity in Lit

<html>
 <head>
   <meta charset="utf-8" />
   <title>&lt;my-element> Demo</title>
   <script src="../node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
   <script src="../node_modules/lit/polyfill-support.js"></script>
   <script type="module" src="../my-element.js"></script>
   <style>
     p {
       border: solid 1px blue;
       padding: 8px;
     }
   </style>
 </head>
 <body>
   <my-element>
     <p>This is child content</p>
   </my-element>
 </body>
</html>

需要注意的是,页面导入了 Polyfill 库,用来确保浏览器能够理解 Web 组件。 同时,它还导入了一个用来通过npm加载Web组件的库,并从父目录导入自定义模块 my-element.js。

Listing 2. Elements of a Lit-based component

import {LitElement, html, css} from 'lit';
/**
* An example element.
*
* @fires count-changed - Indicates when the count changes
* @slot - This element has a slot
* @csspart button - The button
*/
export class MyElement extends LitElement {
 static get styles() {
   return css`
     :host {
       display: block;
       border: solid 1px gray;
       padding: 16px;
       max-width: 800px;
     }
   `;
 }
 static get properties() {
   return {
     /**
      * The name to say "Hello" to.
      * @type {string}
      */
     name: {type: String},
     /**
      * The number of times the button has been clicked.
      * @type {number}
      */
     count: {type: Number},
   };
 }
 constructor() {
   super();
   this.name = 'World';
   this.count = 0;
 }
 
 render() {
   return html`
     <h1>${this.sayHello(this.name)}!</h1>
     <button @click=${this._onClick} part="button">
       Click Count: ${this.count}
     </button>
     <slot></slot>
   `;
 }
 _onClick() {
   this.count++;
   this.dispatchEvent(new CustomEvent('count-changed'));
 }
 /**
  * Formats a greeting
  * @param name {string} The name to say "Hello" to
  * @returns {string} A greeting directed at `name`
  */
 sayHello(name) {
   return `Hello, ${name}`;
 }
}
window.customElements.define('my-element', MyElement);

lit 扩展了 LitElement 基类,styles() 和 properties() 方法都是静态 getter 方法。

styles() 方法返回组件的 CSS,properties() 返回属性。 styles() 使用 Lit 中的 css 方法在模板文字中定义组件范围的 CSS。 properties() 公开组件的反应变量:name和count。 不管是什么情况,返回的对象都定义了属性中的变量类型(例如,name: {type: “String”})。

Listing 3. Public property value

<body>
   <my-element name="Galadriel">
     <p>This is child content</p>
   </my-element>
 </body>

这是反应式框架中很常见的模式,允许状态从父级到子级的单向、向下流动。

Listing 4. Show and hide elements

return html`
     <h1>${this.sayHello(this.name)}!</h1>
     <div ?hidden=${this.count<5}>Not hidden</div>
     <button @click=${this._onClick} part="button">
       Click Count: ${this.count}
     </button>
     <slot></slot>
   `;

Listing 5. Iterating over an array in Lit

static get properties() {
   return {
     name: {type: String},
     count: {type: Number},
     hobbits: []
   };
 }
 constructor() {
   super();
   this.hobbits = ["Frodo","Sam","Merry","Pippin"];
 }
 render() {
   return html`
     <h1>${this.sayHello(this.name)}!</h1>
     <div ?hidden=${this.count<5}>Not hidden</div>
     <button @click=${this._onClick} part="button">
       Click Count: ${this.count}
     </button>
     <ul>
       ${this.hobbits.map((color) =>
         html`<li style="color: ${color}">${color}</li>`
       )}
     </ul>
     <slot></slot>
   `;
 }

以上代码展示了如何添加一个 hobbit 属性,使用四个最著名的 hobbit 对其进行初始化,然后使用渲染函数中的映射进行迭代。

注意:Lit 还提供了一个重复指令,可以用来处理某些情况下的列表状态更改。

Listing 6. getRemoteHobbits

const getRemoteHobbits = async () => {
 const response = await fetch("https://the-one-api.dev/v2/character?race=Hobbit",
   {
     "headers": {
       "Authorization":"Bearer <YOUR API TOKEN HERE>"
     }
   }
 );
 const json = await response.json();
 const hobbits = [];
 for (const h of json.docs){
   hobbits.push(html`<li>${(h.name)}</li>`);
 }
 return hobbits;
}

以上代码使用 fetch 调用来获取字符列表,这些字符由 race=Hobbit 过滤。 JSON 响应组作为一组列表项,可以返回并插入到HTML 模板。UI会显示远程API的hobbit 集合。