Vue.jsにおいてTypeScriptを利用し、クラススタイルによってコンポーネント(class-style component)を記述していく説明をしていきます。
vue cli でプロジェクトを作成します。vue cli については下記関連ページをご覧下さい。
関連ページ
Vue CLI 3 ではじめるVue RouterとVuex入門
バージョンを確認。
1 2 |
$ vue --version 3.8.4 |
プロジェクトの作成
プロジェクトを作成します。今回は「sample-project」という名前にします。
1 |
$ vue create sample-project |
「Manually select features」を選択します。
1 2 3 |
? Please pick a preset: default (babel, eslint) ❯ Manually select features |
「TypeScript」を選択し、今回は下記のように設定しました。
1 2 3 4 5 6 7 8 9 10 11 |
? Please pick a preset: Manually select features ? Check the features needed for your project: ◯ Babel ❯◉ TypeScript ◯ Progressive Web App (PWA) Support ◯ Router ◯ Vuex ◯ CSS Pre-processors ◯ Linter / Formatter ◯ Unit Testing ◯ E2E Testing |
クラススタイルでの記述によってコンポーネントを作成するので、「Use class-style component syntax?」はYesを選択します。
1 2 3 |
? Please pick a preset: Manually select features ? Check the features needed for your project: TS ? Use class-style component syntax? (Y/n) y |
後は適当に選択していきます。インストールが完了すると下記のように表示されます。
1 2 3 4 5 |
🎉 Successfully created project sample-project. 👉 Get started with the following commands: $ cd sample-project $ npm run serve |
TypeScriptとclass-styleによるcomponentの記述
TypeScriptを利用したクラススタイルでのコンポーネント記述の概要をつかむために、すでに生成されている HelloWorld.vue を利用します。下記のように編集しました。
関連ページ
src/components/HelloWorld.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<template> <div class="hello"> <h1>{{ msg }}</h1> <button @click="countNum">+</button> <p>{{ count }}</p> <p>{{ textLower }}</p> </div> </template> <script lang="ts"> import { Component, Prop, Vue, Watch } from "vue-property-decorator"; @Component export default class HelloWorld extends Vue { @Prop() private msg!: string; count: number = 0; text: string = "AIUEO"; countNum(): void { this.count++; } get textLower(): string { return this.text.toLowerCase(); } @Watch("count") onChangeCount(val: number, old: number) { console.log(`新しい数: ${val}, 古い数: ${old}`); } mounted(): void { console.log("ライフサイクルmounted"); } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> 〜省略 </style> |
12行目
単一ファイルコンポーネントによってTypeScriptを利用するためにlang=”ts”を設定します。
13行目
vue-class-component を利用するとTypeScriptかつクラススタイルでの記述ができるようになります。また、このvue-class-component に依存した vue-property-decorator によってVue.jsの機能をデコレータによって追記していくことができます。
例えば15行目の@Componentデコレータによって、Vue.jsのdataオプションは、クラスのプロパティとして記述できるようになります(例:19、20行目)。またmethodsオプションは、クラスのメソッドとして記述できます(例:22〜24行目のcountNum())。
17行目
propsの記述は、@Propデコレータを利用します。名称に「!」を付与する必要があります。
26〜28行目
算出プロパティであるcomputedオプションもメソッドとして記述できます。その場合ゲッター(getter)およびセッター(setter)としてのアクセサを記述する必要があります。上記ではgetアクセサを付与し、8行目で小文字に変換した文字列を表示させています。
30〜33行目
watchオプションは、vue-property-decoratorによる@Watchデコレータによって記述しています。13行目においてwatchをimportしています。
35〜37行目
ライフサイクルフック(lifecycle hooks)もクラスのメソッドとして記述できます。
以上のような感じで、TypeScriptとクラススタイルによってコンポーネントを記述していくことができます。