Prefer function as component's `data` propertyJS-0614
When using the data
property on a component (i.e., anywhere except on new Vue), the value must be a function that returns an object.
At runtime, multiple component instances can be created using the same definition.
When defining a component, if we use a plain object for data
, that same object will be shared by reference across all instances created.
By providing a data function, every time a new instance is created we can call it to return a fresh copy of the initial data.
Imagine, for example, a TodoList component with this data:
data: {
listTitle: '',
todos: []
}
We might want to reuse this component, allowing users to maintain multiple lists (e.g., shopping, wishlists, daily chores, etc.). There's a problem, though. Since every instance of the component references the same data object, changing the title of one list will also change the title of every other list. The same is true for adding/editing/deleting a todo. Instead, we want each component instance only to maintain its own internal state. For that to happen, each instance must generate a unique data object. In JavaScript, this can be accomplished by returning the object from a function:
data: function () {
return {
listTitle: '',
todos: []
}
}
Bad Practice
<script>
Vue.component('some-comp', {
data: {
foo: 'bar'
}
})
export default {
data: {
foo: 'bar'
}
}
</script>
Recommended
<script>
Vue.component('some-comp', {
data: function () {
return {
foo: 'bar'
}
}
})
export default {
data () {
return {
foo: 'bar'
}
}
}
</script>