Tech Blog

プログラミングと技術の情報サイト

Vue.js 3のComposition APIで状態管理

Vue.js 3のComposition APIで状態管理

Vue.js 3で導入されたComposition APIは、コンポーネントのロジックを 関数ベースで整理できる新しい記述スタイルです。 Options APIよりも再利用性が高く、TypeScriptとの親和性も向上しています。

ref と reactive

<script setup>
import { ref, reactive } from 'vue'

// プリミティブ値はref
const count = ref(0)

// オブジェクトはreactive
const user = reactive({
  name: '田中',
  age: 25
})

function increment() {
  count.value++
}
</script>

<template>
  <button @click="increment">{{ count }}</button>
  <p>{{ user.name }}</p>
</template>

computedとwatch

import { ref, computed, watch } from 'vue'

const firstName = ref('太郎')
const lastName = ref('田中')

const fullName = computed(() => `${lastName.value} ${firstName.value}`)

watch(count, (newVal, oldVal) => {
  console.log(`${oldVal} → ${newVal}`)
})

コンポーザブルで再利用

ロジックを useXxx 関数として切り出すことで複数コンポーネントで再利用できます。

// composables/useCounter.ts
export function useCounter(initial = 0) {
  const count = ref(initial)
  const increment = () => count.value++
  const reset = () => count.value = initial
  return { count, increment, reset }
}

まとめ

Composition APIは大規模コンポーネントのロジック整理に特に有効です。 既存のOptions APIとも共存できるため、段階的に移行することも可能です。

← 記事一覧に戻る