I am interested in hearing diverse perspectives on this topic. When working with Vue (and possibly other frameworks), is it more beneficial to prepare non-reactive data through a method and store it in the data for use in the template, or is it preferable to handle this preparation within computed properties?
For instance:
Consider a scenario where we have a page component and an imported modal component that showcases strings created from distinct arrays of strings. These strings are extracted from a single array of objects. The modal receives props related to these strings from the parent component. Once the modal is displayed, its data remains static, therefore reactivity in props is unnecessary.
There are two conflicting methodologies:
- A) Establish a data object for modal props with some preset values. Upon clicking the button, iterate through the data array once, employ Set to generate an array of unique strings, assign the data, and then render the modal.
- B) Create a computed property for each set. Each computed property iterates over the same array.
Highlighted below are code snippets exemplifying both approaches:
A)
{
data: () => ({
modalSettings: { names: '', codes: '' }
}),
methods: {
handleClick () {
const names = new Set()
const codes = new Set()
this.dataArray.forEach(({ name, code ) => {
names.add(name)
names.add(code)
})
this.modalSettings = { names, codes }
}
}
}
B)
computed: {
names () {
return this.dataArray.map(x => [...new Set(x.name)])
},
codes () {
return this.dataArray.map(x => [...new Set(x.name)])
}
}
In approach A, there is more code involved but only one iteration is needed. Despite having a function called first and then updating the data object for template usage, the data ends up existing in two different locations. Is this overly complex? Or would it be preferable to separate the actions performed by a function and result storage into an object?
On the contrary, approach B entails less code and consolidates everything in one place, but requires looping through the array for each property (should this matter?). Is consolidating all operations in a singular location more advantageous?
What makes one approach superior to the other? Is approach A more challenging to sustain and/or less scalable compared to approach B?