$emit
$emit 可用来在子组件中调用父组件中绑定的自定义事件。 this.$emit(‘事件名’,[参数1,参数2…])。
子组件Child中msg与元素input绑定,当输入时,msg会改变同时会调用changeValue函数,
在changeValue函数中会通过$emit调用父组件中的绑定的事件childHandler来改变父组件的msg
<script type="text/javascript">
//全局组件
//
Vue.component('Child',{
data: function () {
return {
msg:'haha'
}
},
template:'<div>' +
'<input type="text" v-model="msg" v-on:input="changeValue()"/>' +
'</div>',
methods:{
changeValue:function(){
// 自定义事件一定通过$emit触发
// $emit(自定义的事件名,消息)
console.log(this.msg);
this.$emit('childHandler',this.msg);
}
}
});
Vue.component('Parent',{
data:function(){
return{
msg:'我是父组件数据'
}
},
template:'<div>' +
'<p> 父组件:{
{msg}}</p>' +
'<Child v-on:childHandler = "childHandler"/>' +//msg被传到子组件中
'</div>',
methods:{
childHandler:function(val){
this.msg += val;
console.log(this.msg);
}
}
});
new Vue({
el:'#app',
template:'<div><Parent/>' +
'</div>'
});
</script>
效果入下:
持续更新中