3
votes

I want to add a property to this inside a component, and I just want it share this property among component's methods, but not use it inside template.

And I find the only way to add a property to this is to add it inside data() function, like

data() {
  return {
    group: {
      children: []
    }
  }
}

and Vue will make the group has __ob__ & getters & setters for all the attributes enter image description here

Should I worry about that? Will it cause performance issue if I keep add property in such way? If so, how do I share a variable among component's methods

2

2 Answers

1
votes

When Vue creates a component instance it walks through each property in your data and creates a getter/setter pair for it in addition to attaching an observer if the property is an object/array. This is in order to make the component reactive to state mutations. It results in a small increase in initialization cost and book-keeping cost, but this is quite negligible for all intents and purposes, so I wouldn't worry too much about that.

There's a great talk titled Demystifying Frontend Framework Performance by Evan You, the creator of Vue, in which he compares different performance aspects of frontend frameworks and describes how Vue's implementation fares in comparison to other frameworks. He outlines the trade-offs he had to make to achieve reactivity and comes to the conclusion that unless you're creating a HUGE app you shouldn't usually worry about a performance hit because of the way Vue works.

Still if you're creating such a huge app and you do run into performance issues you can move any piece of state that isn't reactive to the created hook, and Vue won't track it ..

created() {
 this.group = {
   children: []
 }
}

For objects that won't be modified you can also use Object.freeze() and Vue won't track those either ..

const group = {children: []}
Object.freeze(group)

// Then in your data
data() {
  return {
    group,
  }
}
0
votes

You shouldn't worry about it, the reason is that children object is a reference from the parent object group not a new object, and __ob__ is a observer pattern that a watcher to detect the changes in state and set & get the new values related to the inheritance object, so that in JavaScript memory that's all store in one Object not 2 object, I recommend to see JavaScript: The Hard Parts series for Will Sentance & Advanced Vue.js Features from the Ground Up for Evan You