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

VueJS发出的事件未被同一层次结构中的其他组件捕获

  •  1
  • Morpheu5  · 技术社区  · 8 年前

    我见过 this question 两个都试过了 this.$parent 以及 this.$root 可供选择,但无济于事。情况如下。

    App.vue

    <template>
        <div id="app">
            <global-notifications/>
            <router-view></router-view>
        </div>
    </template>
    
    <script>
    import GlobalNotifications from "./components/GlobalNotifications.vue"
    
    export default {
        name: "app",
        components: {
            GlobalNotifications
        }
    };
    </script>
    

    GlobalNotifications.vue

    <template>
        <div>
            <p>Notifications:</p>
            <p v-for="n in notifications" :key="n.id">{{ n }}</p>
            <b-button @click="internalEmitter">Internal notification!</b-button>
        </div>
    </template>
    
    <script>
    export default {
        data() {
            return {
                notifications: []
            }
        },
        methods: {
            appendNotification(n) {
                this.notifications = [...this.notifications, n]
            },
            internalEmitter() {
                let message = { id: `${Math.floor(Math.random()*1000000)}`, message: 'From the inside!' }
                this.$emit('global-notification', message)
            }
        },
        mounted() {
            this.$on('global-notification', this.appendNotification)
        },
        beforeDestroy() {
            this.$off('global-notification', this.appendNotification)
        }
    }
    </script>
    

    Dashboard.vue

    通过路由器加载。是的,我试着直接从 应用程序.vue

    <template>
        <b-button @click="emitTheThing">External notification!</b-button>
    </template>
    
    <script>
    export default {
        methods: {
            emitTheThing() {
                let message = { id: `${Math.floor(Math.random()*1000000)}`, message: 'From the outside!' }
                this.$emit('global-notification', message)
            }
        }
    }
    </script>
    

    当我点击 Internal notification! 巴顿,我被炒鱿鱼了,一切都按预期进行。但是,当我点击 External notification!

    如我所说,我试着发射 $parent 甚至在 $root ,但我只看到dev工具中的事件,在 <App> 和 <Root> ,分别是。然而 GlobalNotification 孩子似乎没有抓住他们。

    我错过了什么?

    1 回复  |  直到 8 年前
        1
  •  3
  •   tony19 thanksd    8 年前

    问题是 <global-notifications> 组件侦听自身上的事件,而您在根组件上发出事件。请注意,在根组件上发出事件会 不 将事件广播到根的子组件(如您在Vue DevTools中所观察到的)。

    在你的情况下一个快速的解决方法是使用 $root.$on() 以便在根组件上设置侦听器:

    mounted() {
        // this.$on('global-notification', this.appendNotification)
        this.$root.$on('global-notification', this.appendNotification)
    },
    

    $root.$emit() 从任何继承权中的任何组件向根组件发出事件。

    demo