代码之家  ›  专栏  ›  技术社区  ›  PassionateDeveloper

OnChange未在litElement的输入字段中触发

  •  0
  • PassionateDeveloper  · 技术社区  · 5 年前

    我有以下代码:

    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不会触发

    问题1我通过更改修复了

    value="${this.value}"
    

    .value="${this.value}"
    

    甚至我也不知道为什么它有效(在网上发现了这个黑客)。

    但onChange仍然没有开火。。。

    0 回复  |  直到 5 年前
        1
  •  7
  •   Alan Dávalos    5 年前

    由于以下几点,代码没有按预期工作:

    1. 为什么 value 不工作时 .value 做?

    lithtml在这里使用点来区分赋值属性或属性( 价值 分配属性和 .value 财产)

    最简单的思考方式是,属性是在HTML本身上设置的属性,属性设置为表示该节点的Javascript对象。

    现在,这在这种情况下很重要,因为输入元素的value属性仅在首次渲染时从属性中设置,如果以后要更改它,则必须设置属性,而不是属性。 Source

    1. 为什么在代码中更改value属性时没有触发change事件?

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

    如果你想产生某种副作用,不仅在用户输入时交互,而且在代码中修改属性时触发,你可能想使用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>
            `
      }
    }

    有关更多信息,请查看 this part of the LitElement guide

    推荐文章