⚠️ This lesson is retired and might contain outdated information.

Use Properties in Vue Components Using @Prop Decorator with TypeScript

Share this video with your friends

Social Share Links

Send Tweet

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!

[00:00] 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.

[00:23] 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.

[00:42] 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.

[01:04] 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.

[01:19] 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.

[01:39] 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.

[02:06] 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.