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.


    Use Properties in Vue Components Using @Prop Decorator with TypeScript

    Alex Jover MoralesAlex Jover Morales

    With properties we can follow a one-way parent→child flow communication between components. This lesson shows you how you can pass down properties to class based Vue components by using the @Prop decorator from vue-property-decorator.

    We’ll also see how we can set types and even default properties on @Prop!



    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




    Here we have an app and a hello component. The app component is the parent one, so we want to pass down a message property to the hello component. Then the hello component expects that property to be passed, so we can do that in, say, the component options by using the props key. Remember to set the type to string.

    Now, what we can do is we can use a computed property, full message, to concatenate both the internal variable message and the property. As we can see, TypeScript doesn't understand the message property, because it's not part of the class or the parent class.

    We can fix that by creating another class, say hello component, and recreating the message property there. Now, it will stem from it. It stems from Vue. Then it does understand it. We still need to use that full message computed property into the HTML.

    If we try this, we'll see that's working, but there is an easier way to do this by using decorators. We need to install vue-property-decorator, which give us some additional decorators to use in the Vue components.

    Now, we can change this back to stem from Vue, and remove the class that we don't need anymore. We can import prop from vue-property-decorator, and remove the prop property from the component options.

    To use it, it's as simple as decorating with the prop decorator a message variable inside the component, and type it to string. If we run it again, we should see that it's working the same way. We can remove the component import from vue-class-component, because vue-property-decorator re-exports that one. We can write it there.

    By default, the prop decorator takes the type of that variable, in this case a string, as the type of the property. We can explicitly define it by using an object, defining the type, and even the default value. If we go back and remove the property, we should see the default value showing up.