14
7

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 5 years have passed since last update.

Vue.js で子コンポーネントに props を一括で渡す方法

Last updated at Posted at 2019-05-01

沢山のプロパティを持つコンポーネントに値を渡すとき、
以下のように全プロパティについてズラズラ書いていくのはちょっと面倒です。

よくない例
<Profile 
    :id="id" 
    :name="name" 
    :nickname="nickename"
    :address="address"
/>

こういうときは、プロパティ名なしv-bindにオブジェクトを渡すことでプロパティを一括で渡すことができます。

良い例
<Profile v-bind="{id, name, nickname, address}" />

あるいはdata等にオブジェクトを定義しておくとテンプレートがより簡潔に書けます。

良い例
<Profile v-bind="profile" />

(中略)

  data() {
    return {
      profile: {
        id: id,
        name: name,
        nickname: nickname,
        address: address,
      }
    }
  },

蛇足

上述の方法は公式ドキュメントにも一応ちょこっと記載はあるのですが、意外と知らない人も多そうだったので記事にしました。

実際、公式の別の箇所では「プロパティが増えてきたらプロパティ定義を一つにまとめよう」的な別の解決策が書かれています。
しかしながらそれだとプロパティのバリデーションがやり辛くなるため、現在ではバッド・プラクティスではないかと思われます。

現行のバージョンではプロパティ定義を変えずともオブジェクトで渡せるので是非そうしていきましょう。

14
7
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
14
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?