Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Write a Vue Component as a Class in TypeScript


    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    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.

    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.

    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.

    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.

    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.

    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.

    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.

    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.