Home > Article > Web Front-end > Why does data in vue need to use return to return data?
Reason: Data that is not wrapped with return will be globally visible in the project, which will cause variable pollution; while using return wrapping, the variables in the data will only take effect in the current component and will not affect other components.
The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.
Official:
When a component is defined, data must be declared as a function that returns an initial data object, because the component may be used to create multiple instances. If data
were still a pure object, all instances would share a reference to the same data object! By providing a data function, we can call the data
function every time a new instance is created, thus returning a fresh copy of the original data object.
Why does data need to use return to return data in the project?
Data that is not wrapped with return will be globally visible in the project, which will cause variable pollution; after using return, the variables in the data will only take effect in the current component and will not affect Other components.
When a component is defined, data must be declared as a function that returns an initial data object, because the component may be used to create multiple instances. If data
were still a pure object, all instances would share a reference to the same data object! By providing a data function, we can call the data function every time a new instance is created, thereby returning a completely new copy of the original data object.
Analog and reference data types. If function return is not used, the data of each component is the same address in the memory. If one data changes, the other data will also change. This is of course not what we want. Using function return is actually equivalent to declaring new variables, which are independent of each other. Naturally, there will be no such problem; when js assigns the object object, it directly uses the same memory address. So in order to make the data of each component independent, this method is adopted.
If it is not a component, the normal data writing method can directly write an object. For example, two calculators in the same component share data: {num: 0}. Directly sharing objects in JS will cause reference transfer, that is, It is said that all num values will be modified after pressing the plus and minus buttons, so function is used here to return an object instance each time.
[Related recommendations: vue.js tutorial]
The above is the detailed content of Why does data in vue need to use return to return data?. For more information, please follow other related articles on the PHP Chinese website!