Vue 3のリアクティブ性を理解する: refとreactiveの使い所

Vue 3のリアクティブ性を理解する: refとreactiveの使い所

Vue 3ではリアクティブシステムが大幅に改善され、refとreactiveが主要なリアクティブデータ管理手段として提供されています。本記事では、それぞれの使い方と適切な使い所について詳しく説明します。

リアクティブ性とは

リアクティブ性は、データの変更を検知し、自動的にUIを更新する仕組みです。

refとは何か

refは単一の値をリアクティブにするためのAPIです。

import { ref } from 'vue';

const count = ref(0);

function increment() {
  count.value++;
}

reactiveとは何か

reactiveはオブジェクトや配列全体をリアクティブにします。

import { reactive } from 'vue';

const state = reactive({
  count: 0,
  name: 'Vue'
});

function increment() {
  state.count++;
}

refとreactiveの違い

refは単一の値、reactiveはオブジェクトや配列に使用されます。

refの使い所

単一のプリミティブ値をリアクティブに管理する場合に使用します。

reactiveの使い所

複数のプロパティを含むオブジェクトをリアクティブに管理する場合に使用します。

リアクティブデータのアンラップ

テンプレート内ではrefの`.value`が自動的にアンラップされます。

const count = ref(0);
console.log(count.value); // JavaScript内

reactiveとrefの組み合わせ

refとreactiveを組み合わせて使用することも可能です。

const state = reactive({
  count: ref(0)
});

リアクティブデータの深さ

reactiveは深い階層までリアクティブになります。

const obj = reactive({
  nested: {
    count: 0
  }
});
obj.nested.count++;

toRefの活用

reactiveオブジェクトのプロパティをrefとして取り出します。

import { reactive, toRef } from 'vue';

const state = reactive({ count: 0 });
const count = toRef(state, 'count');
count.value++;

toRefsの活用

reactiveオブジェクトのすべてのプロパティをrefに変換します。

import { reactive, toRefs } from 'vue';

const state = reactive({ count: 0, name: 'Vue' });
const { count, name } = toRefs(state);
count.value++;

watchとリアクティブデータ

refとreactiveデータはwatchを使用して変更を検出できます。

import { watch, ref } from 'vue';

const count = ref(0);

watch(count, (newValue, oldValue) => {
  console.log(`Count changed from ${oldValue} to ${newValue}`);
});

リアクティブデータの制限事項

リアクティブシステムが追跡できないケースについても理解しておく必要があります。

refとreactiveの選択基準

単一の値にはref、複数プロパティのオブジェクトにはreactiveを使用します。

まとめ

refとreactiveはVue 3におけるリアクティブシステムの中核です。それぞれの特性を理解し、適切に使い分けることで、より効率的で保守性の高いアプリケーションを構築できます。