Appearance
Vue のリアクティブとは?
Vue.js のリアクティブを使うと、データの変更を検知し自動的に画面を更新することが出来ます。
Vue3 では、ref
と reactive
が提供されています。
ref
はリアクティブで使用する基本の関数です。reactive
はオブジェクトのみ使用可能な関数です。
ref vs reactive
ref
はプリミティブ型(string, number など)もオブジェクト型({name: 'hoge'})も使用できます。
しかし、reactive
はオブジェクト型のみ使用できます。
reactive
を使うとオブジェクトの中身を扱いやすくなりますが、いくつかの注意点があります。
- オブジェクト全体を置換できない
- オブジェクトの中身を分割代入できない
公式ドキュメントにも記載されていますが、基本はref
を使用すると良いでしょう。
サンプル
以下のサンプルは、リアクティブな状態と、非リアクティブな状態の時刻を表示しています。
リアクティブな状態
sample
ボタンをクリックすると、時刻が更新されます。
12:29:51 AM
ソースコードを見る
vue
<template>
<button @click="updateTime">Update Time</button>
<div>{{ timer }}</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
const timer = ref(new Date().toLocaleTimeString());
function updateTime() {
timer.value = new Date().toLocaleTimeString();
}
</script>
<style scoped>
button {
margin: 8px 0;
padding: 8px 16px;
border: 1px solid var(--main-color);
border-radius: 8px;
background-color: var(--main-color);
color: white;
}
</style>
非リアクティブな状態
非リアクティブな状態では、ボタンをクリックしても時刻が更新されません。
sample
ボタンをクリックしても、時刻が更新されません。
12:29:51 AM
ソースコードを見る
vue
<template>
<button @click="updateTime">Update Time</button>
<div>{{ timer }}</div>
</template>
<script setup lang="ts">
let timer = new Date().toLocaleTimeString();
function updateTime() {
timer = new Date().toLocaleTimeString();
}
</script>
<style scoped>
button {
margin: 8px 0;
padding: 8px 16px;
border: 1px solid var(--main-color);
border-radius: 8px;
background-color: var(--main-color);
color: white;
}
</style>
まとめ
Vue3 では、ref
と reactive
を使用してリアクティブな状態を作成することができます。
ref
はプリミティブ型もオブジェクト型も使用できますが、reactive
はオブジェクト型のみ使用できます。
基本は ref
を使用し、オブジェクト型の場合は reactive
を使用します。
また、reactive
を使用する場合は、オブジェクト全体を置換できない、オブジェクトの中身を分割代入できないといった注意点があります。