Become a member
to unlock all features

Level Up!

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


    Extend Vue Components in TypeScript


    This lesson shows how you can extend and reuse logic in Vue components using TypeScript inheritance. It will take you through extending a component, its properties and methods, and how hooks are triggered along the inheritance tree.



    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 will start from this simple component, which has a message variable and a click method. Now, let's create a parent TS component. We need to import Vue and component. Notice that we are creating a TypeScript file, not a Vue file. That's because we are only reusing logic, not CSS or the template.

    As you saw, let's write the component decorator here, and let's put the class in order to create the parent component. Now, we are going to create a parent click method with a console.log() in it. Then we'll see parent clicked in the console.

    Now, we are going to use it in the hello component. First, let's import parent. Then we need to stem from it instead of Vue. Next, we are going to create a button. We will call the parent method from it. Let's check out if this is working. Click, and we can see clicked in the console, and parent click. Both methods are working.

    Now, let's see what happens if we write a click method in the parent, which exists in the child hello component as well. Run this again. We see that only the child click method is triggered. The one from the parent is not.

    You must know that vue-class-component uses the default Vue merging strategy. For example, you cannot use super keyword here. What is happening under the hood is vue-class-component is transforming these classes to objects, and the methods are merged from children to parent, so it gets overwritten.

    Let's see how would that work with instance variables. We have already a message variable in the child hello component. Let's write another in the parent, "hey from parent." Let's see what happens here.

    You can see that the child message is shown, but if we comment it out, then the parent message is shown. Here, it is happening the same as method. The child instance variables overwrite parent ones. Now, let's see how that works for hooks.

    Let's write a created hook in the parent, parent-created. Let's create another one in the hello child component. We'll say child-created. Now, if we run it, they both are called. In contrast to variables or methods, hooks are triggered all from parent to child.