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,
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With