在学习Vue中做一个小笔记。使用Vue创建一个组件的时候,这个组件有局部的数据,但是与Vue实例的data不一样的是,组件中的数据data是一个函数。其原因是组件可能会被多次使用用,如果data是一个属性值就会造成多个该组件的data都是一样的,为了实现同一种组件的数据分离,所以组件中的data是一个函数,这个函数的目的是返回一个单独的数据对象。
talk is cheap, show me the code!
<html>
<head>
<title> hello Vue</title>
<meta charset="utf-8" />
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body >
<div id ="app">
<counter></counter>
<counter></counter>
<counter></counter>
</div>
</body>
<template id="cal">
<div>
{{counter}}
<button @click="increament">+</button>
<button @click="decreament">-</button>
</div>
</template>
<script>
Vue.component('counter', {
template: '#cal',
// 组件中的data必须是一个方法,因为组件可能被多次使用,这时候的data必须要分离开来,使用函数来返回对象可以实现多个同种组件的数据分离!!!!
data(){
return {
counter: 0
}
},
methods: {
increament: function() {
this.counter++;
},
decreament: function() {
this.counter--;
},
}
});
var app = new Vue({
el : '#app',
data: {
},
methods: {
}
})
</script>
</html>
效果: