通过
e
m
i
t
实
现
通
信
上
面
两
种
示
例
主
要
都
是
父
组
件
向
子
组
件
通
信
,
而
通
过
emit 实现通信 上面两种示例主要都是父组件向子组件通信,而通过
emit实现通信上面两种示例主要都是父组件向子组件通信,而通过emit 实现子组件向父组件通信。
对于
e
m
i
t
官
网
上
也
是
解
释
得
很
朦
胧
,
我
按
我
自
己
的
理
解
是
这
样
的
:
v
m
.
emit官网上也是解释得很朦胧,我按我自己的理解是这样的: vm.
emit官网上也是解释得很朦胧,我按我自己的理解是这样的:vm.emit( event, arg )
$emit 绑定一个自定义事件event,当这个这个语句被执行到的时候,就会将参数arg传递给父组件,父组件通过@event监听并接收参数。
父组件
<template>
<div>
<h1>{{title}}</h1>
<child @getMessage="showMsg"></child>
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
data(){
return{
title:''
}
},
methods:{
showMsg(title){
this.title=title;
}
}
}
</script>
子组件
<template>
<h3>我是子组件!</h3>
</template>
<script>
export default {
mounted: function () {
this.$emit('getMessage', '我是父组件!')
}
}
</script>
通过prop实现通信
<!-- 父组件 -->
<template>
<div>
<h1>我是父组件!</h1>
<child message="我是子组件一!"></child> //通过自定义属性传递数据
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
}
</script>
<!-- 子组件 -->
<template>
<h3>{{message}}</h3>
</template>
<script>
export default {
props: ['message'] //声明一个自定义的属性
}
</script>