On the Writing of data in vue instance

problem description

it is found that in vue instances, data can be written in the following two ways:

//
data(){
    return{
        limit:3, 
        ...
    }
}

//
data:{
     limit:3, 
     ...
}

what is the difference between the two methods

Mar.31,2021

either way, there is only one place to keep the data separate, rather than many components pointing to the same data reference.

vue hangs on the dom tree by assembling various components. If data is an Object, imagine what happens when you call components multiple times. Because Object is passed through references, then the data of all component operations point to the same heap through address references, and all operate on the same piece of data, which is bound to cause state confusion, and instance a component will affect the data of component b.
this is just to keep the state independent, so through a function, you can actually return a new data object at a time, even if you don't use the function, as long as you can guarantee that the copy is a new data every time. The function here is just a function factory, an application of the factory model.


vue-cli needs to be in the form of function, and the object form is in the form of


. The first is written in the component component; (the component summary must be written in this way)
the second is written in the vue instance. (the writing in the instance is also fixed and cannot be mixed)


ide/components.html" rel=" nofollow noreferrer "> the component on the official website of Vue has relevant instructions: the data in the component must be a function for each instance to maintain its own data. If data is an object, it means that all components share this data. Will affect each other.

Menu