VueJS computer return best practice
I've using this code over and over again. Wonder if there's a better way to make this shortcut
Here's the example
// items.js
export default [
{ title: 'ABC', href: 'javascript:void(0)' },
{ title: 'DEF', href: 'javascript:void(0)' }
]
// index.vue
<script>
import items from './items.js'
export default: {
computed: {
links() {
let results = []
items.forEach((item,index) => {
item.id = index
results.push(item)
})
return results
}
}
}
</script>
//returned result = { title: 'ABC', href: 'javascript:void(0)', id: 0 }
I just want to add id to each of the object in the computed property, so that I not worry about using v-for="(item, index) in items" :key="index". instead just using v-for="item in links" :key="item.id" in the template
The question:
From the code, you see I declare empty array of results
let results = []then I populate the result from forEach data before I return the result. Is that any better way to do to return each of the loop data without declare empty array and populate it before return the array of that generated data?Sometimes, I not just add id, maybe add another like
item.internal = true. Or level if it's multilevel.
#1 Answers
You could use map method and spread operator to add id to the item :
computed: {
links() {
return items.map((item,index)=>({id:index,...item}))
}
}
Comments
Post a Comment