<g-tabs-head class="red"></g-tabs>
// tabs.vue这样就有了eventBus data(){ return { eventBus: new Vue() } }, provide(){ return { eventBus:this.eventBus } }, created(){ console.log('爷爷的eventBus') console.log(this.eventBus) // this.$emit('update:selected','xxx') } // tabs-head.vie儿子就有了eventBus,其余组件同理 inject: ['eventBus'], created(){ console.log('爷爷给爸爸的eventBus') console.log(this.eventBus) }
created(){ this.eventBus.$on('update:selected',(name)=>{ console.log(name) }) // 这句话的意思是监听selected被更新了,而且执行一个回调,这里监听的多是其它的组件 }, methods: { xxx(){ this.eventBus.$emit('update:selected',this.name) // 这句话的意思是大声喊出来selected更新了 } }
// 咱们的eventBus是g-tabs生成的new Vue(),而app.js监听的g-tabs,是一个vue组件, // 也就是vue组件的事件,而不是new Vue() <g-tabs :selected.sync="selectedTab" @update:selected="yyy"></g-tabs> methods: { yyy(data){ console.log('yyy') console.log(data) } } // 那么组件怎么触发呢 // tabs.vue created(){ this.$emit('update:selected', '这是 this $emit 出来的数据') // 这样写能够触发外面,这里的this 就是当前组件 this.eventBus.$emit('update:selected', '这是 this event $emit 出来的数据') // 这样写不能够触发外面 } // app.js <g-tabs :selected.sync="selectedTab" @update:selected="yyy"></g-tabs> methods: { yyy(data){ console.log('yyy') console.log(data) } }
// tabs-head created(){ this.$emit('update:selected', '这是 tabs-head 抛出来的数据') // 这样写不能够触发外面是由于vue的事件系统是不会冒泡的, //若是g-tabs-head标签是一个div那么是能够触发到g-tabs的由于div是能够冒泡的 } // index.html <g-tabs :selected.sync="selectedTab" @update:selected="yyy"> <g-tabs-head class="red"> <template slot="actions"> <button>设置</button> </template> </g-tabs-head> </g-tabs>
本文由博客一文多发平台 OpenWrite 发布!html