传递数据方–发射事件
通过事件传递$emit(方法名,传递的数据)
接收数据方–监听事件
在mounted()中触发$on(方法名,callback(接收数据的数据))
// 建立一个空的Vue实例,将通信事件挂载在该实例上
// emptyVue.js
import Vue from 'vue'
export default new Vue()
// 兄弟组件a:childa.vue
<template>
<div>
<span>A组件->{{msg}}</span>
<input type="button" value="把a组件数据传给b" @click ="send">
</div>
</template>
<script>
import vmson from "./emptyVue"
export default {
data(){
return {
msg:"我是a组件的数据"
}
},
methods:{
send:function(){
vmson.$emit("aevent",this.msg)
}
}
}
</script>
// 兄弟组件b:childb.vue
<template>
<div>
<span>b组件,a传的的数据为->{{msg}}</span>
</div>
</template>
<script>
import vmson from "./emptyVue"
export default {
data(){
return {
msg:""
}
},
mounted(){
vmson.$on("aevent",(val)=>{//监听事件aevent,回调函数要使用箭头函数;
console.log(val);//打印结果:我是a组件的数据
this.msg = val;
})
}
}
</script>
// 父组件:parent.vue
<template>
<div>
<childa><childa>
<childb></childb>
</div>
</template>
<script>
import childa from "./childa";
import childb from "./childb";
export default {
data(){
return{
msg:""
}
},
components:{
childa,
childb
},
}
</script>
发表评论: