Sometimes on some libraries you find yourself setting the same props to the same values over and over again. Let us use vue-select as an example.
Imagine we have an API that returns an array of objects that looks like:
{
"users": [
{
"user_id": 1001
"name": "John Doe"
},
{
"user_id": 1002
"name": "James Smith"
}
]
}
and that this User Dropdown field is required and want to make it selectable when you press the Tab key. This is really simple to do, all you have to do is import the component and change it like so:
import VueSelect from 'vue-select'
VueSelect.props.clearable.default = false
VueSelect.props.getOptionKey.default = 'user_id'
VueSelect.props.getOptionLabel.default = 'name'
So how does that work? Vue components are just plain objects and what we did above is we mutated that object. You can simply place that in your index.js
file and you don't have to keep on setting the same props over and over.
BUT what if you want 2 versions that you regularly use? Maybe we have public
and admin
pages that requires 2 different version of defaults?
If they differ only by 1 or 2 props, then maybe just live with always setting that single prop.
If not or you're just lazy, then doing the above may or may not work.
If both your public and admin page lives on the same build, doing the above will not work because you'd be mutating the same object. That's basically how node_modules
work but I won't get deeper into it.
import VueSelect from 'vue-select'
const AdminSelect = { ...VueSelect }
AdminSelect.props.clearable.default = false
AdminSelect.props.taggable.default = true
const PublicSelect = { ...VueSelect }
PublicSelect.props.selectOnTab.default = true
export default { AdminSelect, PublicSelect }
Instead of mutating the component directly, we just copy the component instead and change the props accordingly. Now you just simply import what kind of VueSelect you need and type less props.
No need for a wrapper component. Less complex and effective.