@Component デコレーターと Vue クラスの拡張 (extends Vue) が必須。data, props, computed, methods, watch, mounted などを「クラスのプロパティやメソッド」として書く。this を使ってアクセス。// ファイル名: MyComponent.vue
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">+1</button>
</div>
</template>
<script lang="ts">
// クラスコンポーネントを使うためのデコレーター
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
@Component
export default class MyComponent extends Vue {
// props(親から受け取る値)をデコレーターで宣言
@Prop({ default: 0 }) readonly start!: number;
// data に相当する部分
count = this.start;
// computed に相当
get doubleCount() {
return this.count * 2;
}
// methods に相当
increment() {
this.count++;
}
// watch に相当するデコレーター
@Watch('start')
onStartChanged(newVal: number) {
this.count = newVal;
}
// ライフサイクルメソッド
mounted() {
console.log('Component mounted!');
}
}
</script>
| 要素 | 書き方 | 説明 |
|---|---|---|
| Props | @Prop() |
親から受け取るデータ |
| Data | クラスのプロパティ | this でアクセス |
| Computed | get アクセッサ |
this でアクセス |
| Methods | クラスのメソッド | this でアクセス |
| Watch | @Watch() |
特定の変数が変わったときに実行 |
| Lifecycle Hooks | mounted(), created() 等 |
クラス内のメソッドとして定義 |
クラスコンポーネントは「部品が全部1つの大きな機械の中にある設計図」。
thisというリモコンで、どの部品にもアクセスできる。でも、機械が大きくなるとリモコン操作が複雑になる…。
@Component と extends Vue がある」 → クラスコンポーネントの特徴的な形。this でなんでも呼び出す」 → Composition API ではこれがなくなる。