2017-08-25 259 views
2

我正在嘗試創建全局事件總線,以便兩個組件Parent-Child可以相互通信。我四處搜尋;我已閱讀了很多關於全球活動巴士良好模式的文章,但是,我無法找到解決我的情況的方法。我想在我的應用程序中添加通知功能。這是一個文件event.js其中有不同類型的通知:Vue.js中的全局事件總線和通知

Event.js

import Vue from 'vue'; 

export default new Vue({ 
methods: { 
    notifySuccess(message) { 
     this.$emit('notify', 'success', message); 
    }, 

    notifyInfo(message) { 
     this.$emit('notify', 'info', message); 
    }, 

    notifyWarning(message) { 
     this.$emit('notify', 'warning', message); 
    }, 

    notifyDanger(message) { 
     this.$emit('notify', 'danger', message); 
    }, 

    requestError(error) { 
     if (error.response) { 
      this.notifyDanger(error.response.status + ': ' + error.response.statusText); 
     } 
    }, 
}, 
}); 

父組件看起來像這樣

App.vue

<template> 
    <router-view></router-view> 
</template> 

<script> 
    import Event from './js/event.js'; 

    export default { 
     name: 'app', 
     created() { 
      Event.$on('notify', (type, message) => alert(`${type}\n${message}`)); 
     } 
    } 
</script> 

子組件看起來像這樣

Header.vue

<template> 
    <a class="navbar-brand" href="#" @click.prevent="clickTest"></a> 
</template> 

<script> 
    name: 'header', 
    methods: { 
     clickTest() { 
      Event.$emit('notify', 'success', 'Hello World!'); 
      } 
    } 
</script> 

我將在今後的彈出窗口例如notifySuccess顯示一個彈出式的綠色,notifyDanger在紅色,notifyWarning黃色補充。

如何在子組件中創建一個取決於nostrification類型的事件/方法?我究竟做錯了什麼?

PS:抱歉我的英文不好。我希望你能理解我。

回答

0

更換Event.$emit('notify', 'success', 'Hello World!');Event.notifySuccess('Hello World');(你在Event.js中定義的方法,但並沒有使用它們)
,並儘量避免使用內置或保留HTML元素作爲組件ID(如header
那麼你的代碼將不工作任何問題。
參見updated demo