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 のように直接参照可能
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>
ref、reactive、computed の使い分け
種類 | 使いどころ | 例 |
---|---|---|
ref | シンプルな変数(数値、文字列、真偽値) | const count = ref(0); |
reactive | オブジェクトや配列 | const user = reactive({ name: '太郎', age: 30 }); |
computed | 依存関係がある値の計算 | const totalPrice = computed(() => price.value * quantity.value); |
reactive の使いどころ
- オブジェクトや配列など、複数の値を含むデータをリアクティブにするのに適している
- ref とは異なり、オブジェクトのプロパティに .value を付ける必要がない
html
user のプロパティは .value を使わずに user.age++ のように変更可能。<script setup>
import { reactive } from 'vue';
const user = reactive({ name: '太郎', age: 30 });
const incrementAge = () => {
user.age++;
};
</script>
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>