Starter app: https://github.com/alexjoverm/Vue-Typescript-Starter
Writing Vue components as plain objects has very limited capabilities for TypeScript’s IntelliSense. This lesson will show you how to write components as classes to take full potential of TypeScript static typing by using vue-class-component.
Install:
npm install --save vue-class-component
Original file:
<template> <div class="hello"> <h1>{{ message }}</h1> <button @click="clicked">Click</button> </div> </template> <script lang="ts"> export default { data () { return { message: 'Welcome to Your Vue.js App' } }, computed: { fullMessage(){ return `${this.message} from Typescript`; } }, created() { console.log('created'); }, methods: { clicked(){ console.log('clicked'); } } } </script>
- Everything inside "data" mapping to props in class.
- Everything inside "computed" mapping to get method
- "created" lifecycle hook is just a function
- Everything inside "methods" are also just functions.
<template> <div class="hello"> <h1>{{ message }}</h1> <button @click="clicked">Click</button> </div> </template> <script lang="ts"> import Vue from 'vue' import Component from 'vue-class-component' @Component({}) export default class Hello extends Vue { message: string = 'Welcome to Your Vue.js App' get fullMessage() { return `${this.message} from Typescript` } created() { console.log('created'); } clicked(){ console.log('clicked'); } } /* export default { data () { return { message: 'Welcome to Your Vue.js App' } }, computed: { fullMessage(){ return `${this.message} from Typescript`; } }, created() { console.log('created'); }, methods: { clicked(){ console.log('clicked'); } } }*/ </script>