0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vue 3 `defineProps` の基本と活用方法まとめ

Last updated at Posted at 2025-04-03

Vue 3 defineProps の基本と活用方法まとめ

Vue 3 の Composition API と <script setup> 構文の登場により、コンポーネント設計がよりシンプルで直感的になりました。この記事では、その中でも親コンポーネントから子コンポーネントへデータを渡すための仕組みである defineProps の使い方と活用方法について解説します。


目次

  1. こんな人に読んでほしい
  2. defineProps とは
  3. 基本的な使い方
  4. 型をつける(TypeScript対応)
  5. オブジェクト構文でバリデーション
  6. よくある間違い
  7. まとめ

こんな人に読んでほしい

  • Vue 3 の Composition API を使い始めた人
  • <script setup> を使ったコンポーネント設計を学びたい人
  • 子コンポーネントに親からデータを渡す方法を知りたい人

defineProps とは

defineProps は、Vue 3 の <script setup> 構文で使える特別な関数です。
これを使うことで、親コンポーネントから渡された値(props)を簡単に受け取ることができます。

const props = defineProps();

これにより、props オブジェクトを通じて親からのデータを利用できます。


基本的な使い方

親コンポーネント

<template>
  <UserCard name="Tanaka" age="25" />
</template>

<script setup>
import UserCard from './UserCard.vue';
</script>

子コンポーネント(UserCard.vue)

<script setup>
const props = defineProps(['name', 'age']);
</script>

<template>
  <div>
    <p>{{ props.name }} ({{ props.age }}歳)</p>
  </div>
</template>

型をつける(TypeScript対応)

interface Props {
  name: string;
  age?: number; // 任意プロパティ
}

const props = defineProps<Props>();

このようにすると、props に型がつき、IDEの補完や型チェックが効くようになります。


オブジェクト構文でバリデーション

型ではなく、Vue の従来の構文を使いたい場合はオブジェクト形式も使えます。

const props = defineProps({
  name: {
    type: String,
    required: true
  },
  age: {
    type: Number,
    default: 18
  }
});

この方法では、default 値や required などのバリデーションも設定できます。


よくある間違い

❌ オブジェクト構文と TypeScript の型を同時に使う

// これは NG
const props = defineProps<Props>({ ... });

オブジェクト構文と型引数は併用できません。どちらか片方にしましょう。


まとめ

defineProps は Vue 3 の Composition API と <script setup> 構文を使う上で欠かせない存在です。シンプルな使い方から、型定義やバリデーションまで対応できる柔軟さがあります。

  • 受け取るだけなら defineProps()
  • 型をつけたいなら TypeScript を活用
  • バリデーションしたいならオブジェクト構文
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?