We should always use the data function instead of the data property for our component data, except in the root Vue instance. For example, this is considered bad practice:
// .js
Vue.component('foo-component', {
data: { ... }
})
// .vue
export default {
data: { ... }
}
The data in the preceding components should be written as follows:
// .js
Vue.component('foo-component', {
data () {
return { ... }
}
})
// .vue
export default {
data () {
return { ... }
}
}
// .js or .vue
new Vue({
data: { ... }
})
But why? This is because when Vue initiates data, it creates a reference of data from vm.$options.data. So, if the data is an object and when there are many instances of a component, they will all use the same data. Changing the data in an instance will affect the other instances. This is not what we want. So, if data is a function, Vue will use a getData method to return a new object that only belongs to the current instance that you are initializing...