自定义事件:一种组件间通信的方式,适用于:子组件 → 父组件
使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。
1.绑定事件(父组件)
HTML(标签)里的绑定方式:v-on;
JS(Vue)里绑定方式: vue对象.$on(“事件名”,事件处理函数);
2.触发事件(子组件)
vue对象.$emit(“事件名”,参数);
//子组件:
Vue.component('button-counter',{
template: "<input type='button' v-on:click='incrementCounter' v-model='counter' />",
data:function(){
return {
counter:0
}
},
methods:{
incrementCounter:function(){
this.counter += 1
this.$emit('increment')
}
}
});
//父组件:
<div id="app1">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
var app1 = new Vue({
el: '#app1',
data:{
total:0
},
methods:{
incrementTotal:function(){
this.total += 1;
}
}
});
3.解绑事件
this.$off('increment') //解绑组件上的increment事件
this.$off(['increment','increment02']) //解绑组件上多个自定义事件
this.$off() //解绑组件上所有的自定义事件
当组件被销毁时,绑定的事件也自然是失效的。