更改对象属性时触发组件重新渲染

时间:2020-02-12 12:47:24

标签: javascript web-component lit-element lit-html

当被观察对象的属性发生变化时,是否有可能触发组件重新渲染?我知道如果替换对象,该组件将重新渲染,但是当我只是更改其属性时,它不会渲染

class SomeComponent extends LitElement {

      static get properties() {
        return {
          obj: { type: Object, reflect: true }
        }
      }

      constructor() {
        super();
        this.obj = {
           value: 'value' 
        };

      }

      handleClick(value) {
        this.obj.value = value;
      }

      render() {
        return html `
          <div>
            <p>My Value: ${this.obj.value}</p>

            <button @click="${() => this.handleClick('new value')}">Button</button>
          </div>
        `;
      }

    }

 customElements.define('some-component', SomeComponent);

试图使用this.requestUpdate()并且有效,但是我不确定这种解决方案是否经过优化

1 个答案:

答案 0 :(得分:2)

我说在更改obj.value之后立即放置requestUpdate方法是一个好主意。

我在this.requestUpdate()上做了很多工作,通常会触发我想要的更改。

您还可以查看this.updated方法并按以下方式实现它:

updated(changedProperties: PropertyValues): void {
    if (changedProperties.has('obj') triggerMethod()
  }

但这应该为您做到:

 handleClick(value) {
    this.obj.value = value;
    this.requestUpdate()
  }

您担心的是,使用该方法已针对Web标准进行了绝对优化:)