Preface
We need to review the knowledge of prototype chains first. In fact, this problem depends on js, not vue.
function Component(){ = } = { name:'jack', age:22, }
First, we reach a consensus (without this consensus, please add the knowledge of the js prototype chain part):
- Instances, this content in their constructor is different.
- , all instances are common to all instances.
Resolve questions
Based on this, let's take a look at this question:
function Component(){ } = { name:'jack', age:22, } var componentA = new Component(); var componentB = new Component(); =55; (componentA,componentB)
At this time, componentA and componentB data point to the same memory address, and the age has become 55, which leads to the problem!
Next, it is a good explanation for why the vue component needs function:
function Component(){ = () } = function (){ return { name:'jack', age:22, } } var componentA = new Component(); var componentB = new Component(); =55; (componentA,componentB)
At this time, componentA and componentB data are independent of each other, ages are 55 and 22 respectively, so there is no problem!
Summarize
I was suddenly confused about this question, but after thinking about it, I still forgot my basic knowledge too quickly. When I was learning js in the past, the most basic thing was that the difference between the constructor and the prototype was blurred. I didn't expect that this little question of vue allowed me to review the past and learn new things.
This is the end of this article about why data of Vue component must be a function. For more related Vue component data is function content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!