文本输入(输入类型= "text")值在使用具有 LitElement 库的事件更改属性后未更新



源代码:

import { LitElement, html, css } from '../vendor/lit-2.4.0/lit-all.min.js';
export class SearchInput extends LitElement {
static get properties() {
return {
src: { type: String },
items: { type: Array }
}
};
static styles = css`
`;
constructor() {
super();
this.items = [
{ text: 'Hola' },
{ text: 'mundo!' }
];
this.selectedItem = null;
this.text = 'foo';
}
selectItem(item) {
this.selectedItem = item;
this.text = this.selectedItem.text;
}
render() {
return html`
<div class="control">
<input class="input" type="text" value="${this.text}">
<ul class="result-list">
${this.items.map((item) => html`<li @click="${this.selectItem(item)}">${item.text}</li>`)}
</ul>
</div>
`;
}
}
customElements.define('search-input', SearchInput);

在使用LitElement库的事件(this.selectItem(更改属性(this.text(之后,文本输入(输入类型="文本"(值不更新。

我在浏览器中尝试过,但在浏览器控制台中没有错误。我希望输入值在随事件更改属性后更新。

谢谢你的提问!有一些小问题导致值没有更新。

一个问题是this.text不是一个反应性属性,因此更改它不会安排重新渲染。修复方法是将text添加到静态属性中。

第二个问题是,事件侦听器单击处理程序是调用this.selectItems(item)的结果,而不是一个函数,用:@click=${() => this.selectItems(item)}修复。

好处:您可能希望使用live指令.value="${live(this.text)}"将值属性表达式更改为属性表达式。我之所以建议这样做,是因为如果更新value属性,原生input浏览器元素总是会更新其内容,但在更新value属性时,仅在用户与其交互之前更新。live指令有助于告诉Lit对input元素中的活动DOM值进行脏检查。

您的代码包含以下小修复:https://lit.dev/playground/#gist=a23dfbcdfbfcfb7de28b1f7255aaa8ee

或在StackOverflow中运行:

<script type="module">
import { LitElement, html, live } from 'https://cdn.jsdelivr.net/gh/lit/dist@2/all/lit-all.min.js';
class SearchInput extends LitElement {
static get properties() {
return {
src: { type: String },
items: { type: Array },
text: { type: String }, // <- Added this to make `this.text` a reactive property.
}
};
constructor() {
super();
this.items = [
{ text: 'Hola' },
{ text: 'mundo!' },
{ text: 'click these' },
];
this.selectedItem = null;
this.text = 'foo';
}
selectItem(item) {
this.selectedItem = item;
this.text = this.selectedItem.text;
}
render() {
return html`
<div class="control">
<!-- live directive is needed because user can edit the value of the input.
This tells Lit to dirty check against the live DOM value. -->
<input class="input" type="text" .value="${live(this.text)}">
<ul class="result-list">
<!-- Click event is a function -->
${this.items.map((item) =>
html`<li @click="${() => this.selectItem(item)}">${item.text}</li>`)}
</ul>
</div>
`;
}
}
customElements.define('search-input', SearchInput);
</script>
<search-input></search-input>

最新更新