LitElement 对象 属性 为空

LitElement object property is null

我有一个将对象作为 属性 的组件,但由于某些原因,渲染时 this.item 未定义。

@property({type: Object}) item?: {
    family: {iconUrl: string; name: string};
} | null;

static get styles(): CSSResult[] {
    return [
        css`
            ${unsafeCSS(styles)}
        `
    ];
}

render(): TemplateResult {
    if (this.item) { 
       return html`<div>found item</div>
     } else {
       return html`<div>item not found</div>
     }
}
 

在我的 HTML 中,我有以下内容:

const item = {  
   family: {
      name: 'title',
      iconUrl: 'url'
   } 

}

html`<my-component item="${item}"></my-component>

为了接受对象作为参数,我是否遗漏了什么?我试过调整很多东西,比如使 arg .item="{ }" 无济于事。

使用不带字符串引号的 属性 语法:

html`<my-component .item=${item}></my-component>`

您可以告诉 Lit 不检查字符串属性:

@property({attribute: false}) item?: {
    family: {iconUrl: string; name: string};
};

您不需要明确的 null 除非您想以不同于 undefined 的方式处理它(如果您不设置它,这是默认设置)。