Reputation: 2588
I'm reading some Lit Element codes from internet, and I see they declare multiple properties in a single decorator:
@property()
rowData: string = '';
rowDataCount: number = 0;
I'm wondering how it behaves and in this case how can I use type converter:
@property({ type: <String or Number here????> })
rowData: string = '';
rowDataCount: number = 0;
Thank you
Upvotes: 2
Views: 704
Reputation: 191
Yes.Lit can only pass single type
class MyElement extends LitElement {
@property({type: String})
mode?: string;
@property({attribute: false})
data = {};
}
You can see the Lit Source Code about this.
https://github.com/lit/lit/blob/main/packages/reactive-element/src/reactive-element.ts
fromAttribute(value: string | null, type?: unknown) {
let fromValue: unknown = value;
switch (type) {
case Boolean:
fromValue = value !== null;
break;
case Number:
fromValue = value === null ? null : Number(value);
break;
case Object:
case Array:
// Do *not* generate exception when invalid JSON is set as elements
// don't normally complain on being mis-configured.
// TODO(sorvell): Do generate exception in *dev mode*.
try {
// Assert to adhere to Bazel's "must type assert JSON parse" rule.
fromValue = JSON.parse(value!) as unknown;
} catch (e) {
fromValue = null;
}
break;
}
return fromValue;
}
If you pass attribute use html attribute way . Only can pass single type. Because Lit Element extend from Html Element , Html Element's Attribute all convert to "String"
But if you want to pass "String" , "Number ", "Boolean" in single props. You can just pass the value to Component Instance.
For Eg:
<lit-checkbox id="litCheckBox" value="1"></lit-checkbox>
const litCB = document.querySelector("#litCheckBox");
litCB.value = 1; //pass Number type
litCB.value = "2"; //pass String type
Upvotes: 0
Reputation: 3989
You cannot apply the decorator to two members in one go.
I am afraid you were mislead by the two members being right underneath each other. The @property()
decorator only applies to the rowData
member.
The following two snippets are equivalent:
// snippet A: no visual separation
@property()
rowData: String = '';
rowDataCount: number = 0;
// snippet B: with blank lines for visual separation
@property()
rowData: String = '';
rowDataCount: number = 0;
Upvotes: 3