代码之家  ›  专栏  ›  技术社区  ›  Mikulew

Vue中的全局事件总线和通知。js公司

  •  2
  • Mikulew  · 技术社区  · 9 年前

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

    父组件如下所示

    <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>
    

    标题。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:对不起,我的英语不好。我希望你能理解我。

    1 回复  |  直到 9 年前
        1
  •  2
  •   choasia    9 年前

    代替 Event.$emit('notify', 'success', 'Hello World!'); Event.notifySuccess('Hello World'); (您在中定义了方法 Event.js 但没有使用)
    header )
    那么你的代码就可以正常工作了。
    updated demo .