当模板对象属性通过 HTML 字符串提供时,它们未设置
Stencil object properties are not set, when they provided through the HTML string
根据文档,Stencil 组件的 属性 myProperty
@Prop({attribute: "my-prop"})
public myProperty?: object = {};
应使用此 HTML 代码设置:
<my-component my-prop="{hello: 'world'}" ></my-component>
但是,它被设置为默认值(空对象)。布尔值和字符串值工作正常。
这是一个错误,还是我忽略了什么?
Stencil 不会自动解析对象属性。您有两个选择:
- Set the property using JavaScript
- 将其设置为 HTML 属性(有效 JSON)并 manually parse it 设置为可以存储在
@State
属性 中的对象。
我一直包含的手动解析的一个更改是检查它是否实际上是一个对象,以防它是使用 JavaScript 设置的。
@Watch('myObject')
parseMyObjectProp(newValue: string | object) {
if (newValue) {
this.myInnerObject = typeof newValue === 'object' ? newValue : JSON.parse(newValue);
}
}
根据文档,Stencil 组件的 属性 myProperty
@Prop({attribute: "my-prop"})
public myProperty?: object = {};
应使用此 HTML 代码设置:
<my-component my-prop="{hello: 'world'}" ></my-component>
但是,它被设置为默认值(空对象)。布尔值和字符串值工作正常。
这是一个错误,还是我忽略了什么?
Stencil 不会自动解析对象属性。您有两个选择:
- Set the property using JavaScript
- 将其设置为 HTML 属性(有效 JSON)并 manually parse it 设置为可以存储在
@State
属性 中的对象。
我一直包含的手动解析的一个更改是检查它是否实际上是一个对象,以防它是使用 JavaScript 设置的。
@Watch('myObject')
parseMyObjectProp(newValue: string | object) {
if (newValue) {
this.myInnerObject = typeof newValue === 'object' ? newValue : JSON.parse(newValue);
}
}