Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Write a Vue Component as a Class in TypeScript

    Alex Jover MoralesAlex Jover Morales

    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.

    vueVue.js
    typescriptTypeScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 We are going to use this to start the repo. You can find out how to set up TypeScript in a Vue app. Clone it, and run npm install. I've already done both. I prepared a hello component.

    00:12 In this component, you can see an internal state variable called message with a "hello vue" string, a computed full message property, which basically takes the message, and appends from TypeScript, I created hook, and a click method.

    00:30 Let's check if this is working. All right. What we are going to do now is we're going to write this component into a class-based style component. For that, we need to install vue-class-component. Let's run npm install vue-class-component.

    00:56 In the meanwhile, this is installing. Let's first import Vue. Then we also need to import component from vue-class-component. Now, in order to create a class-based component, we have to create a class. Let's write inaudible class hello, and we need to extend from Vue.

    01:20 For now, this is just a plain class, but we still need to tell Vue that this is a component. For that, we are going to use the component decorator. Let's just start rewriting. The component instance variables are written as normal variables.

    01:37 Let's write them as just a string here. He can get rid of the old data property. Next, computer properties are standard getters. We can write here get full message, and return that string. Remember that in getters, you always have to return something.

    02:02 Hooks are written as methods. Let's copy that, and let's remove it. As you can guess, methods are written as methods. They have some differences with hooks, but we will see that later. Let's see if this is still working.

    02:22 Run NPM run dev. All right, everything is working as before, but now, we can take advantage of TypeScript IntelliSense. If we go back and type this-dot, we can see all the properties and methods available in our component.

    Discuss

    Discuss