1.1 简单情况下我们可以通过使用一个空的Vue实例作为中央事件总线,(这里也可以使用app实例,而不需要新建一个空Vue实例)
需要注意的是,调用方法放必须是在created生命周期中执行,这里可以理解为注册事件和调用事件
<!--main.js-->
let bus = new Vue ()
Vue.prototype.bus = bus<template>
<input type="button" value ="组件通讯" @click="communication">
</template>
<script >
export default{
data (){
return {
}
},
methods:{
communication(){
this.bus.$emit("commit" ,'这个A组价方法')
}
}
}
</script><template>
<footer>{{text}}</footer>
</template>
<script>
data(){
text:""
},
created (){
this.bus.$on('commit',result=>{
this.text = result;
console.log(result);
});
}
</script>父组件
<template>
<son :prenMsg ="msg"><son>
</template>
<script>
import son from "./sonContainer.vue"
export default {
data(){
return {
msg : "这是父组件的值"
}
},
components : {
son
}
}
</script>子组件
<template>
<h3>读取到父组件的值为:{{msg}}</h3>
</template>
<script>
data (){
return {
msg : this.prenMsg
}
},
props : ["prenMsg"]
</script>