[Vue 警告]: 在组件定义中,"data" 选项应该是一个返回每个实例的值的函数。
因此,在初始化新的 Vue 实例时,无论将 data:{} 作为对象、data(){return{}} 或 data:function(){return{}} 都没有关系。
但当涉及到组件时就有所不同,让我们尝试一个例子:
<body>
<div id="app">
<counter></counter>
<counter></counter>
</div>
<script>
Vue.component('counter', {
template: '<button v-on:click="counter += 1">{{ counter }}</button>',
data: {
counter:0
}
});
</script>
输出:
[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions.
现在让我们在Vue对象中观察:
<body>
<div id="app">
<button v-on:click="counter += 1">{{ counter }}</button>
<button v-on:click="counter += 1">{{ counter }}</button>
</div>
<script>
new Vue({
el: '#app',
data:{
counter:0
}
});
</script>
</body>
//现在让我们将数据作为组件中的函数,以便能够重复使用同一个组件。
<body>
<div id="app">
<counter></counter>
<counter></counter>
<counter></counter>
</div>
<script>
Vue.component('counter', {
template: '<button v-on:click="counter += 1">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
}
})
new Vue({
el: '#app'
});
</script>
</body>