【问题标题】:lit element unable to render in for each loop点亮元素无法为每个循环渲染
【发布时间】:2021-12-18 12:27:10
【问题描述】:

我有一个像这样的对象属性

pageSizeValues: {
  type: Object
}

像这样被实例化

this.pageSizeValues = {10: 10, 25: 25, 50: 50};

基于此,我想构建一个包含 3 个条目的下拉列表,即通过迭代 pageSizeValues

<vaadin-select @change="${event => this.setLimit(event.target.value)}" value="${this.limit}" placeholder="Page Size" style="width: 80px">
  <template>
    <vaadin-list-box>
      ${Object.entries(this.pageSizeValues).forEach(([key, val]) => 
          {   console.log(key + " " + val);
              html`
                <vaadin-item value=${key}>${val}</vaadin-item>
                 `
            })}
    </vaadin-list-box>
  </template>
</vaadin-select> 

虽然 console.log 在 UI 中正确显示键值对,但我根本没有得到呈现的项目。

当我迭代数组而不是对象时,我设法正确渲染了项目,所以我不确定问题可能出在哪里。

【问题讨论】:

    标签: javascript ecmascript-6 lit-element vaadin14 lit


    【解决方案1】:

    您需要返回 html 值,否则它只是被创建和丢弃。最简单的方法是使用map 而不是forEach

          ${Object.entries(this.pageSizeValues).map(([key, val]) => 
              {   console.log(key + " " + val);
                  return html`
                    <vaadin-item value=${key}>${val}</vaadin-item>
                     `
                })}
    

    【讨论】:

    • 整个render函数返回html值,如下:render(){ return html` } As I mentioned in the post, I can produce the html element when iterating over an array instead of a map / object, e.g.: [ &lt;vaadin-list-box&gt; {this.pageSizeValues.map(item =&gt; html ${item} `)} ]
    • 您现在拥有的代码类似于String value = "Here are the numbers";for (int i=0; i &lt; 10; i++) { "hello" +i; } return value;,因为您没有将在循环中创建的值分配给任何东西
    猜你喜欢
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 2018-04-26
    • 2011-03-04
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多