I am reading up on Vue components, and find their explanation of why data needs to be a function somewhat confusing:
The root instance
var vm = new Vue({
el: '#example',
data: {
message: 'here data is a property'
}
})
A component
var vm = new Vue({
el: '#example',
data: function () {
return {
counter: 0
}
}
})
The Vue docs explain this difference by assigning a global counter variable to each component, and then they act surprised that each component shares that same data... Also they don't explain why they already use a function here.
var data = { counter: 0 }
Vue.component('simple-counter', {
template: '<div>{{ counter }}</div >',
data: function () {
return data
}
})
Of course the data is shared now
<simple-counter></simple-counter>
<simple-counter></simple-counter>
<simple-counter></simple-counter>
When you reference a global object as your data source, it's no surprise that the components don't have their own data. That is also true for root Vue instances that have data as a property.
var mydata = { counter: 0 }
var vm1 = new Vue({
el: '#example1',
data: mydata
})
var vm2 = new Vue({
el: '#example2',
data: mydata
})
So I'm still left with the question why a component can't have a data property?