我使用Litelement创建了一个简单元素,该元素具有两个属性,分别使用字符串的字段和值以及数组类型。当我按如下所示将值作为HTML属性传递时,将发生预期的操作并显示该值(如下图所示)。
<my-el value='[{"use": "official","system": "urn:lumiradx:consult"}]' ></my-el>
import {LitElement, html} from 'lit-element';
import '@material/mwc-select';
import '@material/mwc-list/mwc-list-item';
class MyEl extends LitElement {
static get properties() {
return {
useField: {type: String},
value: {type: Array}
}
}
constructor() {
super();
this.useField = 'true';
this.value = [{}];
}
render() {
if (typeof(this.value) == "string") {
this.value = JSON.parse(this.value);
}
return html`${this.value.map((i, index) => html`
<div id="div">
${this.useField !== 'false' ? html`
<mwc-select class="useField" value="${i.use}" @change="${e => this.value[index].use = e.target.value}">
<mwc-list-item value="usual">Usual</mwc-list-item>
<mwc-list-item value="official">Official</mwc-list-item>
<mwc-list-item value="temp">Temporary</mwc-list-item>
<mwc-list-item value="secondary">Secondary</mwc-list-item>
</mwc-select>` : ''}
</div>
`)}`;
}
}
window.customElements.define('my-el',MyEl);
当我将此元素用作另一个元素中的导入时,会出现问题。在新元素中,第一个元素的值作为第二个对象的对象传递,如下所示。如何读取对象作为属性?
<el-two value='{"identifier":[{"use": "official","system": "urn:lumiradx:consult"}]}'></el-two>
import {LitElement, html} from 'lit-element';
import 'my-el/myel.js';
class ElTwo extends LitElement {
static get properties(){
return {
locationId: {type: String},
value: {type: Array}
}
}
/**default value of properties set in constructor*/
constructor() {
super();
this.locationId = 'true';
this.value = [{}];
}
render() {
if (typeof(this.value) == "string") {
this.value = JSON.parse(this.value);
}
return html`
${this.locationId !== 'false' ? html`<my-el value="${this.value.identifier}" id="locationId"></my-el>` : ''}
`;
}
}
window.customElements.define('el-two', ElTwo);
答案 0 :(得分:0)
您输入的static get properties()
中的类型错误
static get properties(){
return {
locationId: {type: String},
// this is `OBJECT`
value: {type: Object}
}
}
<el-two value='{"identifier":[{"use": "official","system": "urn:lumiradx:consult"}]}' ></el-two>
解决方案很简单,在方括号中使用括号和.
let example1 = html` <el-two .value=${{ identifier: [{ use: 'official', system: 'urn:lumiradx:consult' }] }}> </el-two> `;
let info = { identifier: [{ use: 'official', system: 'urn:lumiradx:consult' }] };
let example2 = html` <el-two .value=${info}></el-two> `;
import { LitElement, html } from 'lit-element';
import 'my-el/myel.js';
class ElTwo extends LitElement {
static get properties() {
return {
locationId: { type: String },
// this is OBJECT
value: { type: Object }
};
}
constructor() {
super();
this.locationId = 'true';
this.value = [{}];
}
render() {
// -> You don't need to do this anymore
// if (typeof(this.value) == "string") {
// this.value = JSON.parse(this.value);
//}
return html` ${this.locationId !== 'false' ? html`<my-el value="${this.value.identifier}" id="locationId"></my-el>` : ''} `;
}
}
window.customElements.define('el-two', ElTwo);