gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:40:44 24 4
gpt4 key购买 nike

我有以下代码:

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 仍然没有触发......

最佳答案

由于以下几个原因,代码无法像您预期的那样工作:

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

  • lit-html 在这里使用点号来区分赋值属性或属性( value 赋值属性和 .value 属性)

    考虑这个问题的最简单方法是,属性是在 HTML 本身上设置的那些属性,而属性被设置为代表该节点的 Javascript 对象。

    现在,这在这种情况下很重要,因为输入元素的 value 属性仅在第一次呈现时从属性设置,如果您想稍后更改它,则必须设置属性,而不是属性。 Source
  • 为什么从代码更改 value 属性时不触发更改事件?

  • 这是因为仅当输入的值因某些用户输入而更改时,才会从输入触发更改事件。 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

    关于javascript - OnChange 未在 litElement 的输入字段中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61430631/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com