上面例子中,可以看到 button-counter 组件中的 data 不是一个对象,而是一个函数:
data: function () {
return {
count: 0
}
}
这样的好处就是每个实例可以维护一份被返回对象的独立的拷贝,如果 data 是一个对象则会影响到其他实例,如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>v-on-data事件</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="components-demo">
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>
<script>
var buttonCounter2Data={count:0}
Vue.component('button-counter',{
data:function(){
//data选项是一个对象,会影响到其他实例;
return buttonCounter2Data
},
template:'<button v-on:click="count++">点击了{{count}}次</button>'
})
new Vue({
el:'#components-demo'
})
</script>
</body>
</html>