Reputation: 492
The properties of one of my Vue components are all required and type Array.
props: {
completed: {
type: Array,
required: true
},
remaining: {
type: Array,
required: true
},
todos: {
type: Array,
required: true
}
}
There are only three props, but If there were more I'd have to repeat the code for all of them. Is there a way to set all props to be required and type Array?
props: {
// the following code should be equivalent to the previous one
completed, remaining, todos: {
required: true,
type: Array
}
}
Obviously the code above doesn't work because this is not how JS objects work.
The best I came up with was this:
// at the beginning of the code
let params = {type: Array, required:true};
// ...
// in the object
props: {
completed: params,
remaining: params,
todos: params
}
Any way to make it more efficient? I'm just looking for a shortcut, since I often discover that there are ways to make code cleaner and more efficient that I didn't know until I asked.
Upvotes: 1
Views: 383
Reputation: 10050
You absolutely should not do this but here is how you can achieve it through spread syntax
const component = {
props: {
...['completed', 'remaining', 'todos'].reduce((obj, key) => (obj[key] = {
required: true,
type: Array
}, obj), {}),
}
}
console.log(component)
Also check out:
You can create a helper function as well:
const component = {
props: {
...myProps(['completed', 'remaining', 'todos'], Array, true)
},
}
console.log(component)
function myProps(arr, type, required) {
return arr.reduce((obj, key) => (obj[key] = { required, type }, obj), {})
}
Upvotes: 2