OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

How to use TypeScript to Create Vue Apps with Vue Class Components

John Au-Yeung
February 8th, 2021 · 5 min read

Vue.js is a popular, easy to use, front end web development framework.

There are several ways we can use it to create Vue.js components.

The most common way is to use the options API, which lets us create components with an object that we export.

An alternative way is to use the vue-class-component library to create class-based components.

Class-based components work better with TypeScript because the value of this is the component class instance. And this is consistent through the component class.

The vue-class-component library is only compatible with Vue.js 2.

In this article, we’ll look at how to create Vue.js apps with class-based components.

Introducing Vue Class Based Components

We can start using class-based components by creating a project with the Vue CLI.

To do this, we run:

1$ vue create app

In the Vue CLI screen, we choose ‘Manually select features’, then choose Vue 2, and then choose TypeScript in the ‘Check the features needed for your project’ question.

Then when we see the ‘Use class-style component syntax?’ question, we choose Y.

Alternatively, we can install the vue-class-component package with:

1$ npm install --save vue vue-class-component

with NPM or:

1$ yarn add --save vue vue-class-component

with Yarn.

Then we enable the experimentalDecorators option in tsconfig.json:

1{
2 "compilerOptions": {
3 ...
4 "target": "es5",
5 "module": "es2015",
6 "moduleResolution": "node",
7 "strict": true,
8 "experimentalDecorators": true,
9 "esModuleInterop": true
10 ...
11 }
12}

Once we set up the project, we can create a simple app with it.

For instance, we can create a counter app by writing:

App.vue

1<template>
2 <div id="app">
3 <Counter />
4 </div>
5</template>
6
7<script>
8import Counter from "./components/Counter";
9
10export default {
11 name: "App",
12 components: {
13 Counter,
14 },
15};
16</script>

src/Counter.vue

1<template>
2 <div>
3 <button v-on:click="decrement">decrement</button>
4 <button v-on:click="increment">increment</button>
5 <p>{{ count }}</p>
6 </div>
7</template>
8
9<script lang="ts">
10import Vue from "vue";
11import Component from "vue-class-component";
12
13@Component
14export default class Counter extends Vue {
15 count = 0;
16
17 public increment(): void {
18 this.count++;
19 }
20
21 public decrement(): void {
22 this.count--;
23 }
24}
25</script>

The key takeaways from the example are:

We create the Counter class that’s a subclass of the Vue class.

We turn it into a component with the Component decorator.

count is class property, and it’s a reactive property.

We shouldn’t initialize reactive properties in constructor because class initialization doesn’t fit in the Vue component lifecycle.

Then increment and decrement methods are methods we can call in the template as we can see from the Counter.vue component.

We access count with this.count as usual.

Class Based Components Hooks and Mixins

The usual component hooks can be added into class-based components.

For instance, we can write:

1<template>
2 <div></div>
3</template>
4
5<script>
6import Vue from "vue";
7import Component from "vue-class-component";
8
9@Component
10export default class HelloWorld extends Vue {
11 mounted() {
12 console.log("mounted");
13 }
14}
15</script>

We added the mounted hooks into our HelloWorld component.

And we should see the console.log run when we mount the component.

Other important hooks include:

beforeCreate - runs when component instance is initialized created - runs after the component instance is created beforeUpdate - runs when data changes but before the DOM changes are applied updated - runs after DOM changes are applied beforeDestroyed - runs right before the component is unmounted destroyed - runs after the component is destroyed

To compile the app to something that users can use in the browser, we run npm run build.

To add mixins, we can create another component class and then call the mixins method to return a mixin class that we can use as a subclass of a class-based component.

For instance, we can write:

1<template>
2 <div>hi, {{ firstName }} {{ lastName }}</div>
3</template>
4
5<script>
6import Vue from "vue";
7import Component, { mixins } from "vue-class-component";
8
9@Component
10class FirstName extends Vue {
11 firstName = "jane";
12}
13
14@Component
15class LastName extends Vue {
16 lastName = "smith";
17}
18
19@Component
20export default class HelloWorld extends mixins(FirstName, LastName) {
21 mounted() {
22 console.log(this.firstName, this.lastName);
23 }
24}
25</script>

We call the mixins function with the component classes we want to incorporate as parts of the mixin.

Then we can access the items from the mixin classes in the HelloWorld class.

Therefore, when we add firstName and lastName in the template, their values will be displayed.

And we see ‘hi, jane smith’ displayed.

In the hooks and methods, we can also get their values as we did in the mounted hook.

Using Vue with TypeScript and why should we use it?

We should use Vue with TypeScript because it lets us annotate the structure of various entities like props, refs, hooks, and more.

Also, methods and reactive properties can have their types annotated.

This means that we get compile-time type checking and we can avoid looking up the contents of objects by logging or checking documentation.

It also avoids data type errors if we have typos and other mistakes.

For example, we can write:

src/HelloWorld.vue

1<template>
2 <div>{{ message }}</div>
3</template>
4
5<script lang="ts">
6import Vue from "vue";
7import Component from "vue-class-component";
8
9const HelloWorldProps = Vue.extend({
10 props: {
11 name: String,
12 },
13});
14
15@Component
16export default class HelloWorld extends HelloWorldProps {
17 get message(): string {
18 return `hi ${this.name}`;
19 }
20}
21</script>

We defined our props by using the Vue.extend method with the props property.

name is the prop.

Then our HelloWorld component extends HelloWorldProps instead of Vue so that we can add the props to the HelloWorld component.

We set the return type of the message getter method to string.

message is a computed property.

The lang is set to ts so we can use TypeScript to write our components.

This is required so Vue CLI can build with the correct compiler.

Also, if modules aren’t working, then we need the esModuleInterop option in the compilerOptions property in tsconfig.json so the TypeScript compiler can import ES modules.

Then we can use the component by writing:

App.vue

1<template>
2 <div id="app">
3 <HelloWorld name="jane" />
4 </div>
5</template>
6
7<script>
8import HelloWorld from "./components/HelloWorld";
9
10export default {
11 name: "App",
12 components: {
13 HelloWorld,
14 },
15};
16</script>

We can define types for reactive properties by writing:

1<template>
2 <div>{{ message }}</div>
3</template>
4
5<script lang="ts">
6import Vue from "vue";
7import Component from "vue-class-component";
8
9interface Person {
10 firstName: string;
11 lastName: string;
12}
13
14@Component
15export default class HelloWorld extends Vue {
16 persons!: Person[] = [
17 { firstName: "jane", lastName: "smith" },
18 { firstName: "bob", lastName: "jones" },
19 ];
20
21 get message(): string {
22 const people = this.persons
23 .map(({ firstName, lastName }) => `${firstName} ${lastName}`)
24 .join(", ");
25 return `hi ${people}`;
26 }
27}
28</script>

We assign an array with the firstName and lastName properties to the persons class property.

We need both properties because the Person interface has firstName and lastName in there and we didn’t specify that they’re optional.

The ! means the class property isn’t nullable.

Then we use this.persons in the message getter to put all the names in the people string.

To add type annotations for methods, we write:

1<template>
2 <div>{{ message }}</div>
3</template>
4
5<script lang="ts">
6import Vue from "vue";
7import Component from "vue-class-component";
8
9interface Person {
10 firstName: string;
11 lastName: string;
12}
13
14@Component
15export default class HelloWorld extends Vue {
16 persons!: Person[] = [
17 { firstName: "jane", lastName: "smith" },
18 { firstName: "bob", lastName: "jones" },
19 ];
20 message: string = "";
21
22 getMessage(greeting: string): string {
23 const people = this.persons
24 .map(({ firstName, lastName }) => `${firstName} ${lastName}`)
25 .join(", ");
26 return `${greeting} ${people}`;
27 }
28
29 mounted() {
30 this.message = this.getMessage("hi");
31 }
32}
33</script>

We have the getMessage method with the greeting parameter which is set to be a string.

The return type of the method is also a string.

To add data types for refs, we write:

1<template>
2 <input ref="input" />
3</template>
4
5<script lang="ts">
6import Vue from "vue";
7import Component from "vue-class-component";
8
9@Component
10export default class Input extends Vue {
11 $refs!: {
12 input: HTMLInputElement;
13 };
14
15 mounted() {
16 this.$refs.input.focus();
17 }
18}
19</script>

We have an input element which assigned the input ref in the template by setting the ref prop.

And then we add the data type to the $refs.input class property.

So we set the type of this.$refs.input to be HTMLInputElement.

And as a result, we should see the focus method, since it’s part of the public API of this type.

SampleApp with Vue Class Based Component and TypeScript

To show you a full example of how to use TypeScript to create a complete Vue App, we can create our own recipe app with class based components.

To do this, we create a TypeScript Vue 2 project with Vue as we did at the beginning of this article.

Then we install the uuid package to let us create unique IDs for the recipe entries along with the type definitions.

We can install them by running:

1$ npm i uuid @types/uuid

with NPM or:

1$ yarn add uuid @types/uuid

to add them with Yarn.

Then we can create the Recipe interface in src/interfaces/Recipe.ts:

1export interface Recipe {
2 id: string;
3 name: string;
4 ingredients: string;
5 steps: string;
6}

Next, we create the RecipeForm.vue in the src/components folder:

src/components/RecipeForm.vue:

1<template>
2 <div>
3 <form @submit.prevent="addRecipe">
4 <div>
5 <label>Name</label>
6 <br />
7 <input v-model="recipe.name" />
8 <br />
9 {{ !recipe.name ? "Name is required" : "" }}
10 </div>
11 <div>
12 <label>Ingredients</label>
13 <br />
14 <textarea v-model="recipe.ingredients"></textarea>
15 <br />
16 {{ !recipe.ingredients ? "Ingredients is required" : "" }}
17 </div>
18 <div>
19 <label>Steps</label>
20 <br />
21 <textarea v-model="recipe.steps"></textarea>
22 <br />
23 {{ !recipe.steps ? "Steps is required" : "" }}
24 </div>
25 <button type="submit">Add Recipe</button>
26 </form>
27 <div v-for="(r, index) of recipes" :key="r.id">
28 <h1>{{ r.name }}</h1>
29 <h2>Ingredients</h2>
30 <div class="content">{{ r.ingredients }}</div>
31 <h2>Steps</h2>
32 <div class="content">{{ r.steps }}</div>
33 <button type="button" @click="deleteRecipe(index)">Delete Recipe</button>
34 </div>
35 </div>
36</template>
37
38<script lang="ts">
39import Vue from "vue";
40import Component from "vue-class-component";
41import { Recipe } from "../interfaces/Recipe";
42import { v4 as uuidv4 } from "uuid";
43
44@Component
45export default class RecipeForm extends Vue {
46 recipe: Recipe = {
47 id: "",
48 name: "",
49 ingredients: "",
50 steps: "",
51 };
52 recipes: Recipe[] = [];
53
54 get formValid(): boolean {
55 const { name, ingredients, steps } = this.recipe;
56 return Boolean(name && ingredients && steps);
57 }
58
59 addRecipe() {
60 if (!this.formValid) {
61 return;
62 }
63 this.recipes.push({
64 id: uuidv4(),
65 ...this.recipe,
66 } as Recipe);
67 }
68 deleteRecipe(index: number) {
69 this.recipes.splice(index, 1);
70 }
71}
72</script>
73
74<style scoped>
75.content {
76 white-space: pre-wrap;
77}
78</style>

Then in App.vue, we write:

1<template>
2 <div id="app">
3 <RecipeForm />
4 </div>
5</template>
6
7<script>
8import RecipeForm from "./components/RecipeForm";
9
10export default {
11 name: "App",
12 components: {
13 RecipeForm,
14 },
15};
16</script>

to render the RecipeForm in our app.

In RecipeForm.vue, we have a form with the input and textarea elements to let us enter the recipe entries.

The @submit directive lets us listen to the submit event which is triggered when we click on the Add Recipe button.

The prevent modifier lets you trigger client-side form submission instead of server-side submission.

The v-model directive lets us bind the inputted values to the properties of the recipe reactive property.

Below the input and text areas, we show an error message if the field doesn’t have a value.

Below that, we render the recipes entries and in each entry, we have a Delete Recipe button to delete the entry.

The key prop set to r.id, which is set to a unique ID so Vue can identify the entry.

In the script tag, we have the RecipeForm component which is a subclass of Vue like a typical Vue class component.

Inside it, we define the recipe property, which has the Recipe type.

We define the initial values of each property.

Also, we have the recipes array which is just an array of objects that implement the Recipe interface.

Then we have the formValid computed property, which we defined as a getter.

We just check if each property of this.recipe has a value.

In the addRecipe method, we check the formValid reactive property to see if all the items are filled in.

If it’s true, then we call this.recipes.push to push an item into the this.recipes array.

The uuidv4 function returns a unique ID.

The deleteRecipe method takes an index parameter, which is a number, then we call splice to remove the entry with the given index.

In the end, we have something that looks like this:

Recipe app

Frontend Monitoring

TypeScript is a great tool to keep common mistakes out, by providing a way to perform static type checks (during the compilation phase), however, there is no substitute to active monitoring of an application. That being said, debugging a web application in production may be challenging and time consuming. OpenReplay is an open-source session replay stack for developers. It helps you replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay lets you reproduce issues, aggregate JS errors and monitor your app’s performance. OpenReplay offers plugins for capturing the state of your Redux or VueX store and for inspecting Fetch requests and GraphQL queries. text Happy debugging, for modern frontend teams - Start monitoring your web app for free.

Conclusion

We can use Vue class components library to add components into our app.

We can also define TypeScript types for each part of a component easily with class components.

We can define TypeScript types for parts of components like methods, refs, class properties, hooks, and more.

More articles from OpenReplay Blog

Improving React application performance: React.memo vs useMemo

As a React developer, you’ve most likely come across situations where optimizing the performance of a component is necessary.

February 8th, 2021 · 8 min read

Integrate Bootstrap in your React Projects with these 2 libraries

Developers have a hard time with CSS or just do not have an eye for design, CSS frameworks come in handy to help them create great designs.

February 6th, 2021 · 5 min read
© 2021 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552