Vue事件總線:this.$bus.$emit與this.$bus.$on


1.創建Vue實例

//main.js
Vue.prototype.$bus = new Vue();

2.發射事件

//GoodsList
this.$bus.$emit("aaa")

3.監聽事件

//home.vue
this.$bus.$on("aaa",()=>{
   this.$refs.scroll.scroll.refresh()
})

4.示例:監聽圖片加載

//GoodsListItem.vue
<template>
<img :src="showImage"
             alt=""
             @load="imgLoad" />
</template>


imgLoad() {
      if (this.$route.path.indexOf("/home") !== 1) {
        this.$bus.$emit("homeImgLoad");
      } else if (this.$route.path.indexOf("/detail") !== 1) {
        this.$bus.$emit("detailImgLoad");
      }
    },
//home.vue
mounted() {
    const refresh = debounce(this.$refs.scroll.refresh, 50);

    this.$bus.$on("homeImgLoad", () => {
      refresh();
    });
  },
//detail.vue
mounted() {
    const refresh = debounce(this.$refs.scroll.refresh, 50);
    this.$bus.$on("detailImgLoad", () => refresh());
  },


免責聲明!

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



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