从功能注入HTML



i之后''聚合物快速游览',并且有一个部分向我们解释了如何根据数组重复元素,但它只向我们展示如何使用模板中继器进行操作,我真的不知道它是如何从后面起作用的。我试图做自己的中继器,但聚合物将代码注射为字符串,例如unescape字符。

代码:

<dom-module id="employee-list">
<template>
    [[employe()]]
</template>
<script>
    class EmployeeList extends Polymer.Element {
      static get is () {
        return 'employee-list'
      }
      constructor () {
        super()
        this.employees = [
          {first: 'Bob', last: 'Li'},
          {first: 'Ayesha', last: 'Johnson'},
          {first: 'Fatma', last: 'Kumari'},
          {first: 'Tony', last: 'Morelli'}
        ]
      }
      employe(employees = this.employees) {
        let template = '<div>Employee List</div>'
        template += employees.map((currentEmployee, id) => {
          return  `<div>Employee ${id}, FullName : ${currentEmployee.first + ' ' + currentEmployee.last}</div>`
        })
        return template
      }

    }
    customElements.define(EmployeeList.is,EmployeeList)
</script>
</dom-module>

结果:

<div>Employee List</div><div>Employee 0, FullName : Bob Li</div>,<div>Employee 1, FullName : Ayesha Johnson</div>,<div>Employee 2, FullName : Fatma Kumari</div>,<div>Employee 3, FullName : Tony Morelli</div>

我想知道它是否是一种注入unescape字符/html的形式@2

您可以在功能中使用querySelector来实现

html

<template>
    <div id="employee-list"></div>
</template>

JS

this.querySelector("#employee-list").innerHTML = template

正如约旦所述,您应该使用dom-repeat

<div> Employee list: </div>
<template is="dom-repeat" items="{{employees}}">
    <div>First name: <span>{{item.first}}</span></div>
    <div>Last name: <span>{{item.last}}</span></div>
</template>

如果您按照获得ID的方式进行操作,则使用dom-repeat有替代方案。您可以使用属性index-as来做到这一点。

<template is="dom-repeat" items="{{employees}}" index-as="id">

您可以在此处找到有关dom-repeat的更多信息:https://www.polymer-project.org/1.0/docs/api/dom-repeat

最新更新