使用 lit-html 时如何指定事件处理程序?

jpi*_*son 5 lit-html

[Writing Templates] 下的主要文档提供了以下用于绑定事件处理程序的示例lit-html

html`<button @click=${(e) => console.log('clicked')}>Click Me</button>`
Run Code Online (Sandbox Code Playgroud)

添加这个带有默认值renderhtml函数导入并调用渲染的简单页面,但是似乎没有渲染按钮。如果删除@click事件绑定,则呈现按钮。一定有我遗漏的东西或库中的严重错误。

版本:0.10.2

以下链接与事件处理程序绑定的工作方式有关lit-html

Kei*_*ith 7

之前接受的答案是错误的。lit-extended已弃用,该解决方法仅在 2018 年的一段时间内有效,同时lit-html切换到新语法。

消费事件的正确方法是:

html`<button @click=${e => console.log('clicked')}>Click Me</button>`
Run Code Online (Sandbox Code Playgroud)

您也可以通过使用handleEvent方法分配对象来配置事件:

const clickHandler = {

    // This fires when the handler is called
    handleEvent(e) { console.log('clicked'); }

    // You can specify event options same as addEventListener
    capture: false;
    passive: true;
}

html`<button @click=${clickHandler}>Click Me</button>`
Run Code Online (Sandbox Code Playgroud)

还有lit-element它为您提供了构建具有 Lit 和 TypeScript 增强功能的 Web 组件的基础,以将创建事件处理程序的样板噪音转移到装饰器中:

@eventOptions({ capture: false, passive: true })
handleClick(e: Event) { console.log('clicked'); }

render() {
    return html`<button @click=${this.handleClick}>Click Me</button>`
}
Run Code Online (Sandbox Code Playgroud)