组件通信之子组件向父组件传递
子向父传值需要通过自定义事件实现
- 子组件定义方法,通过
$emit
方法触发count-change(自定义事件)事件
,并传递参数(可选) - 父级视图绑定
count-change(自定义事件)事件
,通过$event
接收数据,也可也触发父级的方法通过参数
接收数据
示例
<div id="app">
<!-- 视图绑定count-change事件,通过$event接收数据,也可也触发父级的方法通过参数接收数据 -->
<!-- @count-change='count+=$event' 可以直接在视图中通过$event接收数据 -->
<my-com v-for='tem in tems' :key="tem.key" :title='tem.title' @count-change='countnum'>
</my-com>
<p>总数:{{ count }}</p>
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script>
Vue.component('myCom', {
props: ['title'],
template: `
<div>
<span>商品: {{ title }} 数量:{{ num }}</span>
<button @click = 'countadd1'>+1</button>
<button @click = 'countadd3'>+3</button>
</div>
`,
data() {
return {
num: 0
}
},
// 子组件定义方法,通过$emit方法触发count-change事件,并传递参数(可选)
methods: {
countadd1() {
this.$emit('count-change', 1);
this.num++
},
countadd3() {
this.$emit('count-change', 3);
this.num += 3;
}
},
})
new Vue({
el: '#app',
data: {
tems: [{
id: 1,
title: '苹果'
},
{
id: 2,
title: '橙子'
},
{
id: 3,
title: '香蕉'
}
],
count: 0,
},
methods: {
// 通过参数event接收,子级传送过来的数据
countnum(event) {
this.count += event;
}
},
})
</script>