DEV Community

Ahmet Meliksah Akdeniz
Ahmet Meliksah Akdeniz

Posted on • Edited on

Vue.js Basics Part 8 | Emit

Today, I will be talking about emit in Vue.js.

This is part 8 of my Vue.js Basics series, to read part 7, please click here

Emit is the opposite of props. That means, we send (emit) events from child component to parent component. So, how it works:

<script>
export default {
  emits: ['response'],
  created() {
    this.$emit('response', 'hello from child')
  }
}
</script>

<template>
  <h2>Child component</h2>
</template>
Enter fullscreen mode Exit fullscreen mode

As you can see from the code above, we use emits: array to emit something. After that we use the created(){} property.
this.$emit('response', 'hello from child') this takes multiple arguments: first, event name; second, any additional arguments are passed to the event listener. So, when we use emit in parent component, we do that by using @ (v-on:).

Here's parent component:

<script>
import ChildComp from './ChildComp.vue'

export default {
  components: {
    ChildComp
  },
  data() {
    return {
      childMsg: ''
    }
  }
}
</script>

<template>
  <ChildComp @response="(x) => childMsg = x"/>
  <p>{{ childMsg }}</p>
</template>
Enter fullscreen mode Exit fullscreen mode

First, we import the component like so:import ChildComp from './ChildComp.vue', remember syntax import <something> from <path>. Afterwards, register imported component in components option. Here, we've a data that has key property of childMsg, and its value is an empty string initially. However, since we emit something from child component, we can receive that with @something. Since we coded
emits: ['response'] and this.$emit('response', 'hello from child'), we receive by using @response

"(x) => childMsg = x" this line of code assigns childMsg data's value to x parameter in this arrow function. And it comes from child component this.$emit('response', 'hello from child'). Remember, the first argument is the event name, other arguments are passed in arguments to event listener, so it passes 'hello from child'.

To sum it up, today we talked about how to pass events from chiled to parent component. Next, I will be talking about slots in Vue.

Top comments (0)