🎯 1.2 クラスコンポーネントと Composition API の違い


✅ 【要点】

Vue 2.7 では

→ クラスは「this でまとめる」

→ Composition API は「必要な変数や関数を refcomputed で宣言する」


🏗️ 【書き方の違い(具体例)】

クラスコンポーネント(Before)

<!-- Counter.vue -->
<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">+</button>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';

@Component
export default class Counter extends Vue {
  count: number = 0;

  increment(): void {
    this.count += 1;
  }
}
</script>


Composition API(After)

<!-- Counter.vue -->
<template>
  <div>
    <p>{{ count }}</p>
    <button @click="increment">+</button>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';

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


🟢 【特徴比較】

クラスコンポーネント Composition API
構文 クラス(class) + デコレーター ref, reactive, computed, watch
データ クラスのプロパティ refreactive
メソッド クラスのメソッド 関数として setup 内に宣言
computed get で getter を作成 computed 関数で定義
Vuex との連携 this.$store useStore()
ロジックの再利用 mixin composable 関数 (useXXX)
型安全 Decorator による型付け(部分的) ref<number>() など明示的
Vue 3 互換 △(非推奨になりつつある) ◎(Vue 3 完全対応)

🟡 【テスト時の違い】