polymer - 使用 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>
但它不会在我的健康检查组件中呈现标题
问题 :
- 使用 lit.html 渲染对象值?
在我的健康检查组件中渲染标题。
有任何想法吗?
解决方案
我认为您不能从 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 编写
推荐阅读
- c# - 如何减少 XCeed WPF 扩展工具包 Richtextbox 中的行距
- java - JAVA:通过 URL Aurora(mysql)的 JDBC 连接 aws
- c# - 无法弄清楚如何使用 C# 做一个计时器
- python - Skimage 未找到模块错误
- django - Django和Jenkins在执行shell上出现多个错误
- outlook - 对于某些用户,Outlook 加载项在 Outlook 2013 Desktop 上显示为灰色
- javascript - 如何使用 onClick 触发两个函数 reactJs
- java - 如何在 Android 浏览器中添加长按下载弹出菜单?
- python - 类中递归函数的静态方法?
- java - Glassfish 和 MongoDB 连接错误:NoClassDefFoundError