Ryan Griggs
Ryan Griggs

Reputation: 2758

Vue.JS: Why won't parent element receive event? Does parent have to be a custom component?

I am noob to Vue.js. I thought the Events made sense: I assumed they bubbled up through the DOM tree until caught by a parent. But I must be missing something. The following code doesn't work, doesn't generate any errors or warnings, and in the Vue developer tools, I see the event being emitted. What am I missing?

index.html:

<!doctype html>
<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/vuex.js"></script>

</head>
<body>

    <div id="app" @button-clicky="gotevent">
        <div @button-clicky="gotevent">
            <h1>{{ info }} {{ counter }}</h1>
            <button-component />
        </div>
    </div>

    <script src="./main.js"></script>
</body>
</html>

main.js:

Vue.component('button-component', {
    data: function() {
        return {
            count: 1
        }
    },

    methods:
    {
        clicky() {
            this.$data.count++;
            this.$emit('button-clicky');
        }
    },

    template: `<button @click="clicky">Go {{ count }}</button>`
});

const vue = new Vue({
    el: '#app',
    data: {
        info: "this is title.",
        counter: 0
    },

    methods: {
        gotevent() { 
            this.$data.counter++;
            alert('The event was heard!'); }
    }
});

Can't I listen for an event on any parent level above the component emitting it?

I added the listener on both the direct parent <div> and also the 'app' container, but nothing happens and no errors or warnings are thrown.

Upvotes: 0

Views: 354

Answers (1)

kevmc
kevmc

Reputation: 1294

I don't think Vue events bubble like DOM ones, you need to catch them on the emitting component, so <button-component @button-clicky="gotevent" />

Upvotes: 1

Related Questions