自定义事件
在子组件的某个事件中触发父组件的某个自定义事件。
利用v-on绑定自定义事件:
使用$on(eventname)监听事件
使用$emit(eventName, optionalPayload)触发事件
父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。主要靠着父组件注册自定义事件,子组件触发该事件,达到传参等效果。
例1:
<div id="app">
<p>{{all}}</p>
<!-- 可以理解为为example注册了一个fatherCount事件 ,当该事件被触发时会调用addCount函数-->
<example v-on:fatherCount="addCount"></example>
<example v-on:fatherCount="addCount"></example>
</div>
Vue.component('example',{
//为example的子组件注册了click事件,当触发时会调用其组件自己的方法childCount
template:'<button v-on:click="childCount">{{count}}</button>',
data:function(){
return {
count:0
}
},
methods:{
childCount:function(){
this.count++;
//当该方法触发时 会触发fatherCount事件
this.$emit('fatherCount');
}
}
})
new Vue({
el:'#app',
data:{
all:0
},
methods:{
addCount:function(){
this.all++;
}
}
})
例2:
"> <p>{{mess}}</p>
<child v-on:father-way="toChange"></child>
</div>
Vue.component('child',{
template:'<div>\
<input type="text" v-model="message">\
<button v-on:click="childWay">更改</button>\
</div>',
data:function(){
return {
message:'hhhh'
};
},
methods:{
childWay:function(){
//触发父组件的事件,将message传过去
// console.log('child');
this.$emit('father-way',{message:this.message});
}
}
})
new Vue({
el:'#app',
data:{
mess:'emmmm'
},
methods:{
toChange:function(mes){
this.mess=mes.message;
// console.log(mes);
}
}
})
//在DOM中注册自定义事件时不能用驼峰,得用 '-'
理解:子组件在触发父组件注册的自定义事件A的时候,其实就是它触发了事件A,然后事件冒泡到它的父组件,于是,父组件调用相应的函数。