logo头像

前端从未如此简单有趣

By计数器理解自定义事件【PRACTICE】

本文于 572 天之前发表,文中内容可能已经过时。

image-20240722235917924

App.vue

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
<script>
import SubCounter from "./SubCounter.vue";
import AddCounter from "./AddCounter.vue";
export default {
name: "App",
components:{
SubCounter,
AddCounter
},
data(){
return {
counter: 0,
}
},
methods:{
btnClick(count){
this.counter += count
},
subBtnClick(count){
this.counter -= count
}
}
}
</script>

<template>
<div class="app">
<h2>小小计数器:{{counter}}</h2>
<sub-counter @sub="subBtnClick"></sub-counter>
<add-counter @add="btnClick"></add-counter>
</div>
</template>

<style scoped>

</style>

AddCounter.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script>
export default {
name: "AddCounter",
methods:{
addClick(count){
this.$emit('add',count)
}
}
}
</script>

<template>
<div class="add">
<button @click="addClick(1)">+1</button>
<button @click="addClick(5)">+5</button>
<button @click="addClick(1000)">+1000</button>
</div>
</template>

<style scoped>

</style>

SubCounter.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script>
export default {
name: "AddCounter",
methods:{
addClick(count){
this.$emit('add',count)
}
}
}
</script>

<template>
<div class="add">
<button @click="addClick(1)">+1</button>
<button @click="addClick(5)">+5</button>
<button @click="addClick(1000)">+1000</button>
</div>
</template>

<style scoped>

</style>

呈现:

image-20240723000252726