Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Vue's $emit async operation?

Tags:

vue.js

Just quick question, if I call this.$emit, should it be async function or I can expect this.$on's callback get called immediately?

Thanks,

like image 313
Kuan Avatar asked Jan 27 '23 20:01

Kuan


2 Answers

It's called immediately: https://codepen.io/BeniaminH/pen/mdVNpaZ?editors=1111

methods: {
  emitEvent() {
    this.$emit('myEvent')
    console.log('emitted')
  },
},
mounted() {
  this.$on('myEvent', () => {
    console.log('triggered')
  })
}

Logs:

"triggered"
"emitted"
like image 152
Beniamin H Avatar answered Feb 27 '23 00:02

Beniamin H


I landed this question because I had a problem of having "old" values of props after emit. Here's the example

Vue.component('child', {
  props: ['count'],
  methods: {
    emitEvent() {
      this.$emit('increment')
      console.log('after emit', this.count);
      Vue.nextTick(() => {
        console.log('next tick', this.count);
      })
    },
  },
  template: `<div>count {{count}}. <button @click="emitEvent()">emit</button></div>`
})

const example2 = new Vue({
  el: "#root",
  data: {
    count: 100,
  },
  methods: {
    increment() {
      this.count++;
    }
  },
  template: `<div id="example-2"><child :count="count" @increment="increment" /></div>`
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="root"></div>

I expected that after emitting my count value will be updated immediately, but it's not. It's updated in the next tick only. Keep this in mind when you expect that $emit is executed synchronously.

like image 28
Eugene Karataev Avatar answered Feb 27 '23 00:02

Eugene Karataev