【问题标题】:Lit-element checkbox not updated after reset重置后未更新点亮元素复选框
【发布时间】:2020-08-26 16:20:12
【问题描述】:

我是 Lit-element 的新手,我正在尝试修改现有的库。该库基于三个数组创建一个复选框表。数组 AAA 和 BBB 用作索引,数组 CCC 用于设置“checked”属性。

这些数组可以通过 ajax 重新加载,所以初始数据会被重置。

问题是,如果我手动选中/取消选中一个复选框并重置数据,则该复选框不会更新并且手动更改仍然存在。

我尝试将所有三个数组添加到“属性”部分。我还创建了 getter 和 setter。最后我尝试做一个完整的 requestUpdate”,但没有任何效果。

这是一段代码(已编辑:将 ?checked 替换为 .checked):

render(){
    return html`
    ...
        ${this.AAA.map(A => html`
             <tr>
                 ...
                 ${this.BBB.map(B => html`
                     <td>
                        ...
                        <input type="checkbox" .checked=${this.CCC[A].includes(B)} id="${A}:${B}"/>
                        ...
                    </td>
                `)}
            </tr>
        `)}
    ...
    `
}

static get properties() {
    return {
        //(added by me) Same for BBB and CCC
        AAA: { type: Array, hasChanged: (newVal, oldVal) => {
            return true;
        }},
        ...
    };
  }

//(added by me) Same for BBB and CCC
set AAA(newAAA){
    const oldAAA = this.AAA;
    this._AAA = newAAA;
    this.requestUpdate('AAA', oldAAA);
}

get AAA(){
    return this._AAA
}

Ajax 数据可能如下所示:

{
  "AAA": [
    "xxx",
    "yyy",
    "zzz"
  ],
  "BBB": [
    "111",
    "222",
    "333"
  ]
  "CCC": {
    "xxx": [
      "111"
    ],
    "yyy": [
      "222",
      "333"
    ],
    "zzz": [
      "222"
    ]
  }
}

这里有一个小例子,你可以尝试这个问题:https://stackblitz.com/edit/js-fadxme

有什么建议吗? 谢谢。

【问题讨论】:

  • 正如@abraham 建议的那样,我已经用属性(.checked) 替换了属性(?checked),但仍然无法正常工作。 ("webcomponentsjs": "^2.2.10", "lit-element": "^2.1.0")
  • 我添加了一个可以看到问题的工作示例:stackblitz.com/edit/js-fadxme

标签: web-component lit-element


【解决方案1】:

我已经设法在“更新”方法中修改了 shadowRoot/renderRoot。

输入现在声明为:

<input type="checkbox" data-aaa="${A}" data-bbb="${B}" id="${A}:${B}"/>

代替:

<input type="checkbox" .checked=${this.CCC[A].includes(B)} id="${A}:${B}"/>

这里是更新的方法:

updated(changedProperties) {
    var inputs = this.shadowRoot.querySelectorAll("input[type='checkbox']");
    inputs.forEach(elem => { 
      let A = elem.getAttribute('data-aaa');
      let B = elem.getAttribute('data-bbb');
      if(A && B){
        elem.checked = this.CCC[A] ? this.CCC[A].includes(B) : false;
      }
    })
    super.updated(changedProperties);
  }

这里是工作示例:https://stackblitz.com/edit/js-fadxme

不管怎样...最好用哪个,shadowRoot 还是 renderRoot?

【讨论】:

    猜你喜欢
    • 2018-05-06
    • 2022-09-14
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 2018-12-28
    • 1970-01-01
    • 2017-03-07
    • 2018-04-05
    相关资源
    最近更新 更多