litElement 中的输入框 OnChange 事件未触发

6

I have following code:

export class ViTextfield extends LitElement 
{
static get properties() {
    return { 
        value: { type: String }, 
  }

 onChange(e) { console.log(e.target.value) }

 render()
{
    return html`
    <div>

        <div>
            <input id="vi-input" 
                type="text" 
                value="${this.value}"
                @change=${this.onChange} />
        </div>
    </div>
        `
}

目前一切正常运行。 现在,使用我的组件的开发人员应该能够通过属性来设置值,例如:

  document.getElementById('myComponent').value = 1;

现在有两个问题: 1)值本身没有更新,2)onchange事件没有触发

第一个问题我通过改变进行了修复

value="${this.value}"

to

.value="${this.value}"

即使我不知道为什么它能够工作(在网上找到了这个技巧)。

但是仍然无法触发onChange事件...

1个回答

7
代码不能按照你的预期工作,原因如下:
  1. 为什么value不起作用而.value可以?

lit-html在这里使用点号来区分属性值或属性(value指定属性值,.value指定属性)。

最简单的想法是属性是设置在HTML本身上的,而属性是设置在代表该节点的Javascript对象上的。

现在,在这种情况下,这很重要,因为输入元素的值属性只是从属性中设置的,当它首次呈现时,如果您想稍后更改它,则必须设置属性,而不是属性。来源

  1. 当值属性从代码中更改时,为什么不会触发更改事件?

这是因为只有当输入的值由于某些用户输入而更改时,才从输入中触发更改事件。来源

如果您希望在用户交互和代码中修改属性时都触发某种副作用,那么您可能需要使用setter。在您的情况下,应该像这样写:

export class ViTextfield extends LitElement {
  static get properties() {
    return {
      value: {
        type: String
      },
    }
  }

  set value(value) {
    const oldValue = this.value;
    // do some side effect here        
    // set a pseudo-private property that will contain the actual value
    this._value = value;
    // call LitElement's requestUpdate so that a rerender is done if needed
    this.requestUpdate('value', oldValue);
  }

  get value() {
    // return the pseudo-private so that when vitextfield.value is accessed the correct value is returned
    return this._value;
  }

  onChange(e) {
    // update the property so that it keeps up with the input's current value
    this.value = e.target.value;
  }

  render() {
    return html `
    <div>
        <div>
            <input id="vi-input" 
                type="text" 
                value="${this.value}"
                @change=${this.onChange} />
        </div>
    </div>
        `
  }
}

想了解更多信息,请查看LitElement指南的这一部分


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接