计数器

计数器实例:子组件从父组件获取counter数据,子组件有两个button按钮,通过点击事件$emit()向父级传递事件,在父级的emthods写方法,来改变counter值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- 子组件有+-按钮,父组件有counter数据 -->
<div id="app">
<child :childcounter="counter" @subnumber="fathersubnumber" @addnumber="fatheraddnumber"></child>
</div>

<template id="child">
<div>
<h2>当前计数:{{childcounter}}</h2>
<button type="button" @click="childsubnumber">-</button>
<button type="button" @click="childaddnumber">+</button>
</div>
</template>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
const child = {
template:'#child',
data(){
return{
message:'hello child'
}
},
methods:{
childsubnumber(){
this.$emit('subnumber');
},
childaddnumber(){
this.$emit('addnumber');
}
},
props:{
childcounter:{
type:Number,
default:0,
required:true,
}
}
}

const app = new Vue({
el:'#app',
data:{
message:'你好啊',
counter:0
},
methods:{
fathersubnumber(){
this.counter--;
},
fatheraddnumber(){
this.counter++;
}
},
components:{
child
}
})
</script>
</body>
</html>