Vue.js をはじめるにあたっての覚書き

コンポーネント間で値を渡す(親から子へ)

Vue.js では props を使用して、親コンポーネントから子コンポーネントにデータを渡すことができます。

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

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

const parentMessage = ref('こんにちは、子コンポーネント!');
</script>
ChildComponent.vue
<!-- 子コンポーネント -->
<template>
  <p>{{ message }}</p>
</template>

<script setup>
defineProps({ message: String });
</script>

コンポーネント間で値を渡す(子から親へ)

子コンポーネントから親コンポーネントへデータを渡すには emit を使用します。

ParentComponent.vue
<!-- 親コンポーネント -->
<template>
  <ChildComponent @update-message="updateMessage" />
  <p>子からのメッセージ: {{ receivedMessage }}</p>
</template>

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

const receivedMessage = ref('');

const updateMessage = (newMessage) => {
  receivedMessage.value = newMessage;
};
</script>
ChildComponent.vue
<!-- 子コンポーネント -->
<template>
  <button @click="sendMessage">メッセージを送る</button>
</template>

<script setup>
import { defineEmits } from 'vue';

const emit = defineEmits(['update-message']);

const sendMessage = () => {
  emit('update-message', '子コンポーネントからのメッセージ');
};
</script>

ref の使いどころ

  • ref は単純な値(数値、文字列、真偽値など)をリアクティブにする
  • ref を使った変数の値を変更する場合は value を通じて変更する (count.value++)
  • テンプレート内では value を書かなくても count のように直接参照可能

ref は Vue 3 のリアクティブなデータ管理の基本的な方法です。ref を使用すると、変数をリアクティブにし、その値の変更を Vue が検知できるようになります。
html
<template>
  <p>{{ count }}</p>
  <button @click="increment">カウントアップ</button>
</template>

<script setup>
import { ref } from 'vue';

const count = ref(0);

const increment = () => {
  count.value++;
};
</script>

refreactivecomputed の使い分け

種類使いどころ
refシンプルな変数(数値、文字列、真偽値)const count = ref(0);
reactiveオブジェクトや配列const user = reactive({ name: '太郎', age: 30 });
computed依存関係がある値の計算const totalPrice = computed(() => price.value * quantity.value);

reactive の使いどころ

  • オブジェクトや配列など、複数の値を含むデータをリアクティブにするのに適している
  • ref とは異なり、オブジェクトのプロパティに .value を付ける必要がない

html
<script setup>
import { reactive } from 'vue';

const user = reactive({ name: '太郎', age: 30 });

const incrementAge = () => {
  user.age++;
};
</script>
user のプロパティは .value を使わずに user.age++ のように変更可能。

computed の使いどころ

  • computed は依存する値が変更されたときにのみ再計算されるリアクティブな値を作る
  • パフォーマンスを向上させるのに役立つ

html
<script setup>
import { ref, computed } from 'vue';

const price = ref(100);
const quantity = ref(2);

const totalPrice = computed(() => price.value * quantity.value);
</script>

関連記事

最後までご覧いただきありがとうございます!

▼ 記事に関するご質問やお仕事のご相談は以下よりお願いいたします。
お問い合わせフォーム