TIL Nestling Data in Vue
POSTED ON:
TAGS: javascript vue
Best practice to use model in Vue data? Nestled or not?
// EXAMPLE 1: (direct values)
new Vue({
data() {
return {
userName: '',
userEmail: ''
}
}
})
// EXAMPLE 2: (adding a user object)
new Vue({
data() {
return {
user: {
userName: '',
userEmail: ''
}
}
}
})
Example 1 is straightforward.
What's happening with Example 2?
- When Javascript sees an object literal, it' creates an instance of the Object.
- When you nest an object within another object, it's like creating two instances. (more objects referenced in memory)
- Vue adds observers with JS setters on each property & nestled property. More nestled objects, more observers, more work for Vue.
Best Practice?
Use nested objects if:
- You plan to use the nested object on its own later
- The nested object represents something different from its siblings
Avoid as possible nesting if:
- You just want more readability
- You saw it somewhere, so you just copied it
Example from the blog:
// good reason: properties have nothing in common.
new Vue({
data() {
return {
todos: [],
isValid: false,
user: {
Name: '',
Email: ''
}
}
}
})
// bad reason: all the properties belong to the user and there's no other properties
new Vue({
data() {
return {
user: {
Name: '',
Email: '',
todos: [],
isValid: false
}
}
}
})
Related TILs
Tagged: javascript