VUE自定义事件--$emit
自定义事件:
-
当我们需要对子组件中某些特定行为进行监控时,需要让子组件使用$emit来发出通知。
-
$emit发送事件通知时,可以从子组件携带参数到父组件,实现子级向父级通信的功能。
注意
:
此方法只用于子组件向父组件
发送消息(数据)
隔代组件或兄弟组件间通信此种方式不合适
案例:
<body>
<div id="app">
<!-- <son></son>-->
<parent></parent>
</div>
</body>
<script>
let son = {
template:'<div><button @click="getCount">{{count}}</button></div>',
data(){
return{
count:0
}
},
methods: {
getCount(){
this.count++;
if (this.count>10){
this.$emit('cha');
}
}
}
}
let parent = {
template: '<div><p>{{total}}</p><son @cha="getTotal"></son></div>',
components:{
son
},
data(){
return{
total:0,
}
},
/*getTotal是父级的函数*/
methods:{
getTotal(){
this.total++;
}
}
}
let vm = new Vue({
el: "#app",
data: {},
methods: {},
components: {
parent
}
});
</script>