Vue.jsでTypeScriptを利用する

Vue.jsでTypeScriptを利用する

Vue.jsでTypeScriptを利用する手順。

環境

  • OS  CentOS 8.0.1905 (Core)
  • node v12.13.1
  • npm 6.13.2
  • @vue/cli 4.1.1

プロジェクト作成

type-testという名前で作成します

vue create type-test

Manually select featuresを選択

Vue CLI v4.1.1
? Please pick a preset: 
  default (babel, eslint) 
❯ Manually select features 

TypeScriptを選択します。

? 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
? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? No
? Where do you prefer placing config for Babel, ESLint, etc.? In package.json
? Save this as a preset for future projects? No

起動してみます。

cd type-test
npm run serve

ブラウザから http://プライベートIP:8080にアクセスすると、Welcome to Your Vue.js + TypeScript Appと表示されています。

テキストデータを表示してみます。

type-test/src/components配下のHelloWorld.vueを下記のように編集します。

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h1>{{ text }}</h1>
  </div>
</template>

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

@Component
export default class HelloWorld extends Vue {
  @Prop() private msg!: string;
  text: string = "Hello Text";

  get textLower(): string {
    return this.text.toLowerCase();
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

ブラウザから http://プライベートIP:8080にアクセスするとテキストが表示されます。