Sunday, 7 January, 2018 UTC


Summary

All developers using component-based architectures, such as Vue’s and React’s, know that creating reusable components is hard, and most of the time you end up having a lot of properties in order to make it easier to control and customize a component from the outside.
That’s not bad, but it’s true that passing lots of properties can get a bit cumbersome and ugly. However, there’s a way for every Vue.js component style to cope with it.
Let’s take as an example the vuetify’s button component, one of the simplest ones. Say that we want to pass the same bunch of properties in most cases:
<v-btn color='primary' href='https://alligator.io' small outline block ripple > Hello Meat </v-btn> 
It could make sense to have them in a separate file, let’s call it props.js:
export const buttonProps = { color: 'primary', small: true, outline: true, block: true, ripple: true, href: 'https://alligator.io' } 
JSX and Render Functions
Since they give you more power and flexibility when it comes to rendering, it’s fairly easy to pass multiple properties at once.
In a render function:
import { buttonProps as props } from './props.js'; export default { render: h => h( 'v-btn', { props }, 'Hello Meat' ) }; 
And in JSX:
import { buttonProps as props } from './props.js'; const data = { props } export default { render: h => <v-btn {...data}>Hello Meat</v-btn> }; 
Using a Vue.js template
What about using the Vue.js DSL (or template)? No worries, that’s also possible. All you need to do is to use the v-bind directive. Given an object that you must define in the data option of your component it will bind all properties:
<template> <v-btn v-bind='buttonProps'> Hello Meat </v-btn> </template> <script> import { buttonProps } from './props.js'; export default { data: () => ({ buttonProps }) } </script> 
With this trick you won’t need to fill your template with repeated properties at several places in your app, while still being able to use the beloved template tag.
Wrapping Up
Passing multiple properties to a component can be simplified using the examples mentioned in this article. This is especially useful for presentational and third party components that have lots of properties.
Keep in mind that the examples used here are merely educational. If you want to stay DRY (Don’t Repeat Yourself) there could be better approaches depending on the specific case, such as creating your own wrapper components.