Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

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


    Create your own Decorators in Vue with TypeScript

    Alex Jover MoralesAlex Jover Morales

    We’ve used @Watch, @Inject and more decorators from vue-property-decorator. In this lesson however we will guide you through creating your own decorators in order to add common functionality to your Vue components using TypeScript.



    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




    Vue-class-component give us a utility function called createDecorator. We're going to create a log decorator. This function takes a factory function with two arguments, component and key, as parameters.

    Let's just do a couple of console logs here for the component, and the same for the key. With this, we have created already our first decorator, and we can apply it to anything.

    Let's create a variable name equal to inaudible , and apply the log decorator there. We'll see in the console that key is the name of that variable, which is name in this case, and the component argument is the instance of this component, which we can have full access.

    We can apply this decorator to computed properties or a message. Let's create a message computed property, and then we'll see that we have two logs now -- one for the name variable, and the other for the computed property.

    If we inspect the component, we see that it has a computed property in its instance. Right now, this log decorator implementation doesn't accept any argument. If we want to pass an argument, we can wrap the createDecorator function into a higher-order function.

    We can pass through simple message. Let's put it as optional. Then we can log it inside.

    Now, we have to use this decorator with parentheses. If we don't pass anything, we'll see undefined in the console, but if we pass something in the first one, it will show up.

    Let's see another example. We're going to create a no catch decorator in order to make the computed properties disable the catch. We can access the component computed property, and disable the catch there.

    Let's set the component type into any, so then TypeScript doesn't complain about it. If we apply this to our message computed property, if we inspect the component log inside the console, we'll see that the catch for this computed property disabled.