0

It seems that when I try to emit an event in mounted it doesn't get triggered! therefore It doesnt show up in devtools

main.js

const app = new Vue({
    el: '#app',

    mounted() {
        console.log('asd');
        this.$emit("clicked", "someValue");

    }
});

--

<body>

    <div id="app">

       <h1>vuejs</h1>

    </div>

    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
    <script src="main.js"></script>   

</body>

Why is that? and how can I do it?

rook99
  • 1,034
  • 10
  • 34

2 Answers2

2

It works fine - your console.log outputs as it should, and you're emitting the event without issues.

In the code you've shown, though, you haven't set anything up to listen to the emitted event... Here's a simple, contrived example of how to do that with this.$on:

const app = new Vue({
    el: '#app',

    mounted() {
        console.log('asd');

        this.$on('clicked', function(value) {
            alert('clicked!' + value);
        });

        this.$emit("clicked", "someValue");
    }
});

Demonstration: https://codepen.io/anon/pen/qKeWxJ

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
1

When you add an event handler in the parent's mounted lifecycle event for an event that is emitted in a child's mounted event, the handler will not catch the event emitted by the child because the handler is added after the child has already emitted the event. Basically the cycle of events is like this.

Parent's create Child's create Child's mounted Parent's mounted Obviously there are other lifecycle events that occur, but that's the sequence that matters in this case.

If you want to handle an event emitted in the child, you need to create the handler (call $on) before the child's mounted event.

Is it possible to emit from mounted in Vuejs?

niclas_4
  • 3,514
  • 1
  • 18
  • 49
  • 2
    This is good general info (have an upvote), but OP's example doesn't have any parent/child communication happening at all. – ceejayoz Jul 06 '18 at 21:56