🎯 4.1 クラスコンポーネントの基本形


✅ 【要点】

Vue 2.7 では、vue-class-componentvue-property-decorator を使うことで

TypeScript のクラス構文でコンポーネントが書ける

@Component@Prop などのデコレーターで

コードがスッキリ&型安全に書けるのが特徴。


🟢 【必要なパッケージ】

npm install vue-class-component vue-property-decorator


🏗️ 【クラスコンポーネントの基本形】

<!-- src/components/HelloWorld.vue -->
<template>
  <!-- nameプロパティを表示 -->
  <div>Hello, {{ name }}!</div>
</template>

<script lang="ts">
// クラスコンポーネント用のimport
import { Vue, Component, Prop } from 'vue-property-decorator';

// @ComponentでクラスをVueコンポーネントとして定義
@Component
export default class HelloWorld extends Vue {
  // 親から受け取るprop(name)を定義、型はstring
  @Prop({ default: 'World' }) readonly name!: string;

  // dataの代わりにクラスのプロパティとして定義
  message: string = 'Welcome to Vue with Class Components';

  // computedの代わり
  get upperName(): string {
    return this.name.toUpperCase();
  }

  // methodsの代わり
  greet(): string {
    return `Hello, ${this.name}!`;
  }
}
</script>


🟠 【1行ずつ解説】

意味
import { Vue, Component, Prop } クラスコンポーネント用のデコレーターを読み込み
@Component このクラスをVueのコンポーネントとして認識する
@Prop({ default: 'World' }) 親から受け取るname。なければ'World'になる
message: string = ... dataに相当する。this.messageで使える
get upperName() computedプロパティ。this.upperNameで使える
greet() methodsに相当する。this.greet()で呼べる

🧪 【使い方】

<!-- 親コンポーネント -->
<template>
  <HelloWorld name="Vue" />
</template>

<script lang="ts" setup>
// コンポーネントをインポート
import HelloWorld from './components/HelloWorld.vue';
</script>

出力: