首页 > 解决方案 > 使用 lit.html 渲染对象

问题描述

设想 :

在我的webComponent - health-check.js文件中,我有:

  static get properties() {
    return {
      plan:Object,
    };
  }

 <div class="body"><p class="title">${this.plan.title}</p></div>


在我的index.html文件中, 我传递 json 如下:

<health-check plan='{ "title" : "Solution Architecure",
 "status" : "Approved" }'></health-check>

但它不会在我的健康检查组件中呈现标题


问题 :

标签: polymer

解决方案


我认为您不能从 html 文件传递​​对象,因为它只是 html 而不是 lit-element 或 lit-html 并且 lit-html 在这种情况下似乎没有尝试解析值(更新我刚刚找到了另一种定义属性的方法,见下文)。但是当然你仍然可以传递字符串并在元素内解析它。

在 index.html 中

<health-check planString='{
  "title": "Solution Architecure",
  "status": "Approved"
}'>
</health-check>

在 health-check.js 中

class HealthCheck extends LitElement {
  static get properties () {
    return {
      planString: String
    }
  }

  render () {
    return html`
      <div class='body'>
        <p class='title'>${JSON.parse(this.planString).title}</p>
      </div>
    `
  }
}

但我建议将您的代码包装在单个入口点中,例如 my-app 元素

在 index.html 中

<my-app></my-app>

在 app.js 中

class App extends LitElement {
  render () {
    return html`
      <health-check .plan='${{
        title: 'Solution Architecure',
        status: 'Approved'
      }}'>
      </health-check>
    `
  }
}

在 health-check.js 中

class HealthCheck extends LitElement {
  static get properties () {
    return {
      plan: Object
    }
  }

  constructor () {
    super()
    this.plan = {}
  }

  render () {
    return html`
      <div class='body'>
        <p class='title'>${this.plan.title}</p>
      </div>
    `
  }
}

更新

您可以定义属性类型来告诉 lit-element 如何序列化和反序列化。

class HealthCheck extends LitElement {
  static get properties () {
    return {
      plan: {
        type: {
          fromAttribute (value) {
            return JSON.parse(value)
          }
        }
      }
    }
  }

  render () {
    return html`
      <div class='body'>
        <p class='title'>${this.plan.title}</p>
      </div>
    `
  }
}

注意:这段代码用 lit-element 0.6.x 和 lit-html 0.11.x 编写


推荐阅读