SRC \core\instance\ state-js-initdata () SRC \core\instance\ state-js-initdata ()

The function returns a new data object instance each time it executes

The source code is as follows: according to the data type of data to carry out different logic processingThe test code is as follows

<! DOCTYPEhtml> 
<html> 
<head> 
    <title>Vue event processing</title> </head> 
<body> 
    <div id="demo"> 
        <h1>Why does the Vue component Data have to be a function?</h1> 
        <comp></comp> 
        <comp></comp> 
    </div> 
    <script src=".. /.. /dist/vue.js"></script> 
    <script> 
        Vue.component('comp', { 
            template:'<div @click="counter++">{{counter}}</div>'.data: {counter: 0}})// Create an instance
        const app = new Vue({ 
            el: '#demo'});</script> 
</body> 
</html> 

Copy the code

The program doesn’t even pass vUE detection

As you can see from the source code below, the creation of the VUE root instance and the creation of the VUE component instance are different processing logic

Summary: Vue components can have multiple instances. If you define data as objects, they will share a single data object. Therefore, state changes will affect all component instances, which is not reasonable. It is defined as a function, and will be used as a factory function to return the new data object in initData, effectively avoiding the problem of state pollution between multiple instances. This limitation does not exist in the Vue root instance creation process, also because there can only be one root instance and you do not need to worry about this situation.