$emit 实现并不是父组件向子组件发送消息来进行通信,而是通过子组件向父组件发送消息来进行通信的,这个上和其他的稍微有点不同。
对于$emit,我先是看了下官网的介绍说明
有些看不懂,后来自己差了些资料:
其实也就是:vm.$emit( event, arg )
$emit 绑定一个自定义事件event,当这个这个语句被执行到的时候,就会将参数arg传递给父组件,父组件通过@event监听并接收参数:
<template>
<div>
<h1>{{name}}</h1>
<child @getMessage="showMsg"></child>
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
data(){
return{
name:''
}
},
methods:{
showMsg(name){
this.name=name;
}
}
}
</script>
<template>
<h3>我是小超!</h3>
</template>
<script>
export default {
mounted: function () {
this.$emit('getMessage', '我是大超!')
}
}
</script>
输出结果: