【问题标题】:LitElement object property is nullLitElement 对象属性为空
【发布时间】:2021-05-19 22:23:08
【问题描述】:

我有一个将对象作为属性的组件,但由于某种原因,在渲染 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-component lit-element lit


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 啊,这看起来确实有效,但是当对象作为字符串传递时它不起作用。 &lt;my-component .item={"iconUrl": "123", "name": "123"}&gt;&lt;/my-component&gt;。我尝试添加 type: Object ,因为我认为这是为了自动解析属性,但它似乎不起作用。
    • @JamesIves 不,您必须添加自己的转换器,例如 @property({ converter: { fromAttribute: attr =&gt; JSON.parse(attr) } })
    猜你喜欢
    • 2017-08-30
    • 2016-05-04
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多