0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Litで構造化データを属性としてコンポーネントに渡す

Posted at

はじめに

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;
      }
    });
  }

おわりに

ここまでの内容がわかってやっと最低限使えるようになった感じがしました
とにかくドキュメント以外に参考になるものがすくなく大変でした

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?