10
2

自己紹介

初めまして!@satoseriと申します
今年新卒として、株式会社エル・ティー・エスに入社し、エンジニアとして自社サービスの開発運用を担当しています。
フロントエンドのフレームワークの一つとして活用されているVue.jsの基本的な機能であるPropsに関して、復習も兼ねてまとめてみました。拙い文章ですが、最後まで読んでいただけると幸いです。

Propsとは

propsはコンポーネントに登録できるカスタム属性のことです。
親コンポーネントから子コンポーネントにデータを渡すための仕組みです。

親から子コンポーネントへのデータの渡し方

子コンポーネントでmessageプロパティとして定義されている文字列型の値を親コンポーネントから子コンポーネントへ受け渡しています。

ChildComponent.vue
<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>

<script>
export default {
  props: {
    message: String,
  },
  setup(props) {
    return {
      message: props.message,
    };
  },
};
</script>

ParentComponent.vue
<template>
  <div>
    <h1>親コンポーネント</h1>
    <ChildComponent :message="parentMessage" />
  </div>
</template>

<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent,
  },
  setup() {
    const parentMessage = ref('親からのメッセージ');
    return { parentMessage };
  },
};
</script>

Propsで主に定義されるもの

1 type: テキストや数値などのデータの型を設定

propsにはどのような値が入るかtypeによってチェックを行う

<script>
defineProps({
  name: {
    type:String,
  },
});
</script>

2 default:デフォルト値の設定

<script>
defineProps({
  name: {
    type: String,
    default: '山田花子',
  },
});
</script>

3 Required:必須なpropsかを設定

<script>
defineProps({
  name: {
    type: String,
    required: ture, //tureの場合は必須である
  },
});
</script>

まとめ

propsを定義することで異なるコンポーネント間でデータを簡単に受け渡すことができます。
propsを活用することで、渡されるデータの型が期待通りかどうかの検証や同じコンポーネントを異なる場所で異なるデータとともに使用でき、コードの冗長性の減少や再利用性の向上につながります。

vueをこれから始めるどなたかの参考になれば幸いです。
最後まで見ていただきありがとうございました!

引用・参照

10
2
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
10
2