父组件通过子组件的props属性可以将父组件的数据传送给子组件
子组件可以通过$emit(),将自定义事件传递给父组件

一.子组件需要传递自定义事件的场景
在红色大组件中进行网络请求获取数据,通过子组件中props,将红色组件中的数据传递给各个蓝色组件。但是,当我点击左侧边蓝色组件中的手机数码时,该蓝色组件要将点击手机数码的事件发送给红色组件,红色组件根据发送过来的事件再次发送网络请求获取手机数码的数据,右侧边的组件又通过props获取手机数码的数据并展示。

二、子组件如何向父组件传递自定义事件
首先展示按钮组件
<div id="app">
<cpn1></cpn1>
</div>
<template id="cpn1">
<div>
<!--在button中展示目录的名字-->
<button v-for="item in categories">{{item.name}}</button>
</div>
</template>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/*子组件构造器*/
const cpnC1 = Vue.extend({
template:'#cpn1',
data(){
return{
categories:[
{id:'001',name:'手机数码'},
{id:'002',name:'电脑办公'},
{id:'003',name:'家用电器'},
{id:'004',name:'美妆护肤'},
]
}
}
})
/*根组件*/
const app = new Vue({
el: '#app',
components: {
cpn1:cpnC1
}
})
</script>

1.当点击按钮时触发点击事件,在事件处理函数中向父组件发送自定义事件

2.在事件处理函数btnclick(item)中发送自定事件
$emit(自定义事件,参数)

3.父组件监听子组件传递的自定义事件

4.在父组件的methods中设置监听到自定义事件的事件处理函数

全部过程:
点击子组件的button触发点击事件,在点击事件中发送自定事件,父组件对自定义事件进行监听,并在methods中处理自定义事件,最后打印出当前button的对象。

网友评论