Home > Software engineering >  For vue data, is it necessary to define data or is it just convention
For vue data, is it necessary to define data or is it just convention

Time:06-24

For vue data, for every tutorials I have seen, it seems that data variables first defined as return value when creating vue instance like below:

app = createApp({
    data() {
        return {
            someData: null,

        }
    },
}

I wonder if this practice is some way necessary or if it is just a convention, because I could simply define new data like this.someData2 in mounted or methods and it seems to work pretty much the same way.

CodePudding user response:

the data option must be an function so every vue instance can maintain a separate copy of the return object,so it won't infect other instance

CodePudding user response:

I could simply define new data like this.someData2 in mounted or methods and it seems to work pretty much the same way ?

Answer is Yes, You can add a new property directly to this without including it in data. However, properties added this way will not be able to trigger reactive updates.

But we use the data option to declare reactive state of a component. The option value should be a function that returns an object. Vue will call the function when creating a new component instance, and wrap the returned object in its reactivity system.

Please do through this official documentation of Reactivity Fundamentals for better understanding.

  • Related