We first refer to the explanation given on vUE’s official website:
A component’s data option must be a function that allows each instance to maintain a separate copy of the returned object
First, let’s look at a simple prototype chain.
`function VueComponent(){}
VueComponent.prototype.$options = {
data:{
name:'zf',
}
}
let vc1 = new VueComponent()
vc1.$options.data = 'lx'
let vc2 = new VueComponent()
console.log(vc2.$options.data)`
Copy the code
As you can see, the instance VC1 changed the name value to “lx”, and the new instance VC2 also accesses the changed value of “lx”.
This is because VC1 and VC2 instance objects are operating on attributes on the VueComponent constructor stereotype object when they operate on $options. The instance object’s implicit stereotype property is equal to its constructor’s display stereotype property, so they point to the same memory space. This results in the two objects’ data not being independent and contaminating each other.
Based on the above results, go back to the data attribute in our Vue component.
When a component is reused multiple times, multiple instances are created. These instances use the same constructor, and if data is an object, then all components share the same object. In order to ensure the data independence of components, each component must return an object as the state of the component through the data function.
core/global-api/extend.js line:33
Sub.options = mergeOptions(Super.options, extendOptions) function mergeOptions() { function mergeField(key) { const strat = strats[key] || defaultStrat options[key] = strat(parent[key], child[key], vm, key) } } strats.data = function(parentVal: any, childVal: any, vm ? : Component ): ? Function { if (! If (childVal && typeof childVal! == 'function') { process.env.NODE_ENV ! == 'production' && warn('The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm) return parentVal } return mergeDataOrFn(parentVal, childVal) } return mergeDataOrFn(parentVal, childVal, vm) }Copy the code
Conclusion:
A component is used multiple times using the same constructor. In order to ensure that different instances of data of a component do not conflict and that the data in the component is independent of each other, data must be a function so that the components do not affect each other.