什么叫事件中心
- 一個(gè)事件可以滿足監(jiān)聽 (.$on)岖妄,觸發(fā) (.$emit)们镜,取消監(jiān)聽(.$off)那他就可以叫事件中心
- 所以一個(gè)new vew()可以構(gòu)成一個(gè)實(shí)踐中心
如何使用EventBus
- 在data里面聲明一個(gè)evetBus
- 在最外層組件的屬性上加一個(gè)provide屬性
data(){
return {
eventBus: new Vue()
}
},
provide () {
return {eventBus: this.eventBus}
},
- 然后只需要在子組件或?qū)O子組件注入缴渊,那么該組件就能訪問到這個(gè)事件中心了
inject:['eventBus'], //注入
mounted() {
//監(jiān)聽eventbus
this.eventBus.$on('update:selected',(name,vm)=>{
let headLeft = this.$el.getBoundingClientRect().left
let {width,left} = vm.$el.getBoundingClientRect()
this.$refs.line.style.width = width + 'px'
this.$refs.line.style.left = left-headLeft +'px'
})
},
- 需要注意的是仑乌,事件中心出發(fā)的事件和vue原生的事件是不一樣的兑燥,不能使用@綁定在html標(biāo)簽里面
一個(gè)完整的例子
- 爺爺組件注冊(cè)eventBus亮瓷,并觸發(fā)事件
- this.$options.name:組件的name,this.name:組件的data或prop的name
data(){
return {
eventBus: new Vue()
}
},
provide () {
return {eventBus: this.eventBus}
},
mounted() {
this.$children.forEach(vm=>{//父組件的兒子
if (vm.$options.name === 'WheelTabsHead'){
vm.$children.forEach(childVm=>{ //父組件的孫子
if (childVm.$options.name === 'WheelTabsItem' && childVm['name'] === this.selected){
//update:selected觸發(fā)事件
this.eventBus.$emit('update:selected', this.selected,childVm)
}
})
}
})
},
inject:['eventBus'],//注入事件
mounted() {
//監(jiān)聽update:selected事件
this.eventBus.$on('update:selected',(name,vm)=>{
let headLeft = this.$el.getBoundingClientRect().left
let {width,left} = vm.$el.getBoundingClientRect()
this.$refs.line.style.width = width + 'px'
this.$refs.line.style.left = left-headLeft +'px'
})
},
created: function () {
//監(jiān)聽update:selected事件
this.eventBus.$on('update:selected', (name) => {
this.active = this.name === name
})
console.log(this.name + this.disabled)
},
methods:{
changeSelected(){
if (this.disabled === true){return}
//觸發(fā)update:selected事件降瞳,傳值
this.eventBus.$emit('update:selected',this.name,this)
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者