首页 > 解决方案 > LitElement 对象属性为空

问题描述

我有一个将对象作为属性的组件,但由于某种原因,渲染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="{ }"无济于事。

标签: web-componentlit-elementlit

解决方案


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

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

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

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

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


推荐阅读