1. 程式人生 > 實用技巧 >Vue事件匯流排:this.$bus.$emit與this.$bus.$on

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());
  },