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.
[00:00] 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.
[00:17] 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.
[00:34] 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.
[00:53] 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.
[01:08] 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.
[01:31] We can pass through simple message. Let's put it as optional. Then we can log it inside.
[01:40] 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.
[01:57] 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.
[02:13] 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.