案例 1:
- 在子组件中两个按钮+1和-1,点击后修改count
- 整个操作的过程还是在子组件中完成,但是之后的展示交给父组件
- 这样,我们就需要将子组件中的count,传给父组件的某个属性,比如total
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<cpn @deliver-count="receive"></cpn>
父组件中的total:{{total}}
</div>
<template id="counterCpn">
<div>
<button @click="incr">+</button>{{count}} <button @click="decr">-</button>
<button @click="deliver">发送count给父组件中的total</button>
</div>
</template>
<script>
const app = new Vue({
el: "#app",
data: {
total: 0,
},
methods: {
receive(count) {
this.total = count;
}
},
components: {
cpn: {
template: "#counterCpn",
data() {
return {
count: 0,
}
},
methods: {
incr() {
this.count++;
},
decr() {
this.count--;
},
deliver() {
this.$emit('deliver-count', this.count)
},
},
},
},
})
</script>
</body>
</html>
案例2:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<!-- cpnClick方法监听item-click自定义事件,不加括号,默认接收item-click内的参数 -->
<cpn @item-click="cpnClick"></cpn>
</div>
<!-- 子组件模板 -->
<template id="cpn">
<div>
<button v-for="(item,index) in categories" @click="btnClick(item,index)">{{item.name}}</button>
</div>
</template>
<script>
//子组件
const cpn = {
template: "#cpn",
data(){
return{
categories:[
{id:'aaa',name:'热门推荐'},
{id:'bbb',name:'家用家电'},
{id:'ccc',name:'畅销手机'},
{id:'ddd',name:'好吃食品'},
]
}
},
methods:{
btnClick(item,index){
//发射事件给父组件,'item-click'是自定义事件名,后面是发送的数据
this.$emit('item-click',item,index);
}
}
}
//父组件
const app = new Vue({
el: "#app",
data: {},
methods: {
cpnClick(item,index){
console.log('cpnClick',item,index);
}
},
components:{
cpn,
}
})
</script>
</body>
</html>