通过在一个组件上触发事件,兄弟组件监听该事件,来传递数据。
在Vue实例上创建一个事件总线(event bus),通过把事件交由该event bus来处理,并由兄弟组件监听event bus上的事件来在兄弟组件间进行通信。
实例:
<body>
<div id="app">
<my-input></my-input>
<my-content></my-content>
</div>
<script>
//事件总线 event bus
//Vue 实例
Vue.prototype.bus = new Vue();
const vm = new Vue({
el: "#app",
components: {
myContent: {
data(){
return {
content: ''
}
},
created(){
//监听事件
this.bus.$on('click', (content)=>{
console.log(content);
this.content = content;
});
},
template: `<div>{{content}}</div>`
},
myInput: {
data (){
return {
inputValue: ''
}
},
methods: {
handleClick(){
console.log(this.inputValue);
this.bus.$emit('click', this.inputValue);
}
},
template: `<div>
<input type="text" v-model="inputValue">
<button @click="handleClick">提交</button>
</div>`
}
}
});
</script>
</body>