LitElement中的自定义属性访问器

时间:2020-06-26 11:03:15

标签: javascript lit-element lit-html

为了学习如何编写自定义属性访问器,我试图创建与默认访问器具有相同行为的属性访问器。我正在使用来自文档here的示例,但我正在努力使其正常运行。以下导致Uncaught RangeError: Maximum call stack size exceeded错误。如果删除getter和setter,则该元素将按预期工作,并呈现两个包含“ hello”和“ world”的div。 如何为属性data创建自定义属性访问器,其行为与默认属性访问器(未定义getter和setter的行为)相同?

import { LitElement, html } from "lit-element";
import { render } from "lit-html";

class TestElement extends LitElement {
  static get properties() {
    return {
      data: { type: Array },
    };
  }

  set data(val) {
    let oldVal = this.data;
    this.data = val;
    this.requestUpdate("data", oldVal);
  }

  get data() {
    return this.data;
  }

  constructor() {
    super();
    this.data = [];
  }

  render() {
    return html`${this.data.map(d => html` <div>${d}</div>`)}`;
  }
}
customElements.define("test-element", TestElement);

render(html`<test-element .data=${["hello", "world"]}></test-element>`, window.document.body);

我正在尝试重新创建此示例的行为,该行为将按预期方式呈现“ hello”和“ world”:

import { LitElement, html } from "lit-element";
import { render } from "lit-html";

class TestElement extends LitElement {
  static get properties() {
    return {
      data: { type: Array },
    };
  }

  constructor() {
    super();
    this.data = [];
  }

  render() {
    return html`${this.data.map(d => html` <div>${d}</div>`)}`;
  }
}
customElements.define("test-element", TestElement);

render(html`<test-element .data=${["hello", "world"]}></test-element>`, window.document.body);

1 个答案:

答案 0 :(得分:0)

set data(val) {
    let oldVal = this.data;
    this.data = val; // THIS causes an infinity loop as you do invoke the setter again
    this.requestUpdate("data", oldVal);
}

相反,设置另一个变量

set data(val) {
    let oldVal = this.data;
    this.__data = val;
    this.requestUpdate("data", oldVal);
}

get data() {
    return this.__data;
}