Autoplay

    Extend Vue Components in TypeScript

    Alex Jover MoralesAlex Jover Morales

    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.

    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:02 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.

    00:28 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.

    00:53 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.

    01:31 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.

    01:53 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.

    02:13 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.

    02:24 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.

    02:40 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.

    Discuss

    Discuss