What is Vue-Types?
Props belong to components like the missing semicolon belongs in every good developer joke.
In my opinion a very helpful package to simplify this finger exercise of the experienced developer is "vue-types". But wait a minute! Can't Vue do Prop-Validation already out of the box? Why do I need an extra package here?
Why I should try Vue-Types | The advantages
- Vue-types is strongly inspired by React's PropTypes. Therefore it is very intuitive for many developers who are switching to Vue.
- We can significantly reduce the overhead in Prop validation. Imagine the Prop "age". With Vue's home remedies, a validation would look like this:
age: %7B type: Number, validator(value) %7B return Number.isInteger(value) %7D, default: 0, %7D,
With Vue-Types we achieve the same result in this way:
But the real beauty of Vue-Types lies in the custom validators
Custom Validation in Vue-Types
Let's imagine that our app has now become more complex. We have some components that receive a user object. The object is relatively complex, it receives standard data like address and date of birth, as well as the preferred payment method, which is stored in an object that contains, for example, a hash, a validUntil and various other strings, integers, dates and booleans.
Vue-Types now allows us to place a customValidator in a central location in our app. This way we do not have to write a validation in each of our components. A simple
does the job. Another advantage: If something changes in the content of the object, we only have to make an adjustment at one central place!
When shouldn't I use Vue-Types | Disadvantages
- You know your application best. If you only have a few components in front of you, or validation of props is not a big deal, implementing Vue-Types might be a bit like taking a sledgehammer to crack a nut. Especially if there is no use case for custom validation.
- Let's get real: We have implemented Vue-Types in an application with over 250 components. Refactoring all this takes time and nerves. Besides the mere implementation, it definitely makes sense to look at why this component needs this particular prop and which type is the right one here. But there is a big gain as well: We found some places where validation was not correct or even wrong and therefore we were able to fix these errors immediately.
- Especially the validation of objects can sometimes get on your nerves when using Vue-Types. Although an error is thrown if an object does not correspond to the expected structure, what exactly is missing or different remains unclear sometimes. So the only thing you can do is to find the error yourself. Especially with complex validations, this can really take some time.