1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| 有些时候我们可能遇到一些需要往另一个组件中传递数据的情况,这种时候我们需要用到一个叫做事件总线的技术,让他在组件与组件之间起到桥梁的作用
1.首先我们先定义一个事件总线 var bus=new Vue() 2.在某个组件中使用这个事件总线 Vue.component('child1', { template: ` <div> <input type="text" v-model="text"> <button @click="handleClick">点我传递数据到另一个组件</button> </div> `, data() { return { text: '' } }, methods: { handleClick() { console.log(this.text) bus.$emit('suibian',this.text) } } })
3.在另外一个组件上监听事件总线的变化 Vue.component('child2', { template: ` <div> 收到的消息是:{{recv_text}} </div> `, data(){ return { recv_text:'' } }, mounted(){ bus.$on('suibian',(item)=>{ console.log('收到了',item) this.recv_text=item }) }, })
|