vue.js中$emit的理解
作者:
秒速五厘米
因为子组件进行传值其父组件应该有一个触发条件,而去知道何时触发可以进行监听在这里你可以使用点击事件也可以是其他的事件,,子组件向父组件传递值如果需要父组件去进行显示 那么这个显示条件或者说值得获取一定要有触发的 ,而原理呢就是事件监听
也可以说是发布订阅模式
emit 其实就是从改组件中绑定的事件events 找到对应的事件上所有的方法,然后遍历执行

例子:$emit('increment1',[12,'kkk']),直接看是懵逼的有没有,可以先告诉你,就是触发自定义事件increment1(或者函数名吧),[]为参数
上案例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment1="incrementTotal"></button-counter>
<button-counter v-on:increment2="incrementTotal"></button-counter>
</div>
</body>
<script src="vue/vue.min.js"></script>
<script>
Vue.component('button-counter',{
template:'<button v-on:click="increment">{{ counter }}</button>',
data:function(){
return {counter: 0}//组件数据就是这样的,函数式的,请注意
},
methods:{
increment:function(){
this.counter += 1;
this.$emit('increment1',[12,'kkk']);//$emit
}
}
});
new Vue({
el:'#counter-event-example',
data:{
total:0
},
methods:{
incrementTotal:function(e){
this.total += 1;
console.log(e);
}
}
});
</script>
</html>先看组件 button-counter
绑定了事件click————>increment
然后 this.counter += 1; this.$emit('increment1',[12,'kkk']);
这边就是触发事件 increment1,参考文献里面有点乱,这边是不是清晰多了
然后
v-on相当于监听吧,就触发 incrementTotal
输出// [12, "kkk"]
有没有很清晰,若有理解不对的地方,请指正
https://www.cnblogs.com/hhweb/p/6678716.html