はじめに
Litを使ってWebコンポーネントを開発している中で、Reactのように構造化データをタグに渡して使いたいと思ったのですが、公式のドキュメントをみても簡単に解決できなかったのでまとめていきます
方法1 : 文字列として渡す
文字列として属性に渡して、オブジェクトとして受け取る方法です
属性は文字列でいれないといけないようで、受け取りはobject
にすることでJsonParseなどをしていい感じにしてくれています
render() {
return html`
<user-card
user='{
"username": "watanabe",
"age": "25",
"prefecture": "埼玉県",
"topImage": "https://source.unsplash.com/random?human",
"subImages": "https://source.unsplash.com/random?fruit, https://source.unsplash.com/random?sweets, https://source.unsplash.com/random?cat, https://source.unsplash.com/random?school",
"selfIntroduction": "こんにちは。"
}'
></user-card>
`;
}
export class UserCard extends LitElement {
static properties = {
user: {
type: Object,
attribute: "user",
},
};
方法2 データとして渡す
これがやりたかったことになります
@property({ type: Object })
user = {
username: "じん!!",
age: "25",
prefecture: "埼玉県",
topImage: "https://source.unsplash.com/random?human",
subImages: [
"https://source.unsplash.com/random?fruit",
"https://source.unsplash.com/random?sweets",
"https://source.unsplash.com/random?cat",
"https://source.unsplash.com/random?school",
],
selfIntroduction: "test",
};
return html`
<user-card .user="${this.user}"></user-card>
`
ポイントは属性に.
をつけることです。.user
とすることで構造化データとして認識してくれるようでした
export class UserCard extends LitElement {
static properties = {
user: {
type: Object,
attribute: "user",
},
};
受け取りは1と変わらないです。
おまけ
ユーザーはsubImageという配列を持っていますが、これは更新があっても子コンポーネントには伝わりません (Reactと同じく)
なのでUserのsubImagesが変わったときに更新が入るようにUserに対してupdated
を定義すると他の更新をキャッチしてsubImages
の更新ができました
static properties = {
user: {
type: Object,
attribute: "user",
},
};
updated(changedProperties: any) {
changedProperties.forEach((oldValue: any, propName: any) => {
if (propName === "user") {
this.topImage = this.user.topImage;
this.subImage = this.user.subImages;
}
});
}
おわりに
ここまでの内容がわかってやっと最低限使えるようになった感じがしました
とにかくドキュメント以外に参考になるものがすくなく大変でした
参考