vue bus事件總線 非父組件$on觸發的解決辦法


在組件中使用$bus事件總線之后,如果自定義事件是相同的時候,如果在多個父組件中監聽,在進行路由跳轉后會出現非父組件$on觸發的問題

home子組件

methods:{
    imageLoad(){
      this.$bus.$emit('item-image-load')
    }
  }

home中監聽

 mounted() {
    this.busRefresh = ()=>{
      this.$refs.scroll.refresh()
    }
    this.$bus.$on("item-image-load", this.busRefresh)
  }

detail子組件

methods:{
    imageLoad(){
      this.$bus.$emit('item-image-load')
    }
  }

detail中監聽

mounted() {
    this.busRefresh = () =>{
      if(this.$refs.scroll) {
        this.$refs.scroll.refresh()
      }
    }
    this.$bus.$on("item-image-load", this.busRefresh)
  }

可以發現home和detail的子組件都發射了一個名為item-image-load的自定義事件,那么問題來了,在組件路由的切換過程中,home->detail中,home中依舊能監聽到,這樣就非常不好的,為了避免這個問題,實現當前組件的子組件發射自定義事件在當前父組件中監聽到,那就必須要在路由跳轉離開當前組件之前進行銷毀,如果組件使用了緩存(keep-alive),那么就在deactivated中銷毀,否則在組件的destroyed中銷毀(每個頁面都會有自己的生命周期,默認在離開組件后都是進行destroyed銷毀)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM