Introduction
Recently, I started learning VueJS, and this article is part of the series of my notes while learning it. In the last post, I covered how to pass the data to the component. This post will cover how to send data from the component to the parent.
Initial component
We can start with the initial component set. A parent component will display the number how many times the button was clicked, and a child component that contains a button and send an update to the parent when a button is clicked.
<!--Parent component-->
<template>
<div>
<div>Number of clicks: {{counter}}</div>
<CounterButton></CounterButton>
</div>
</template>
<script>
import CounterButton from './CounterButton.vue';
export default {
components: {CounterButton},
data() {
return {
counter: 0
}
},
methods: {}
}
</script>
<!--Child component-->
<template>
<div>
<button type="button" @click="handleClick">Click</button>
</div>
</template>
<script>
export default {
data() {
return {}
},
methods: {
handleClick() {
console.log("handle click")
}
}
}
</script>
Sending data to parent
When sending data from the child component to the parent, we do it by broadcasting events. Every component has access to the event emitter function, and you can access it in the component with this value. When calling it, the first parameter is the event type and the second data you want to send if any.
this.$emit(EVENT_TYPE, PAYLOAD);
For our example, I will call the event increment-counter, and as I will always increment by one, there is no need to pass any data to it.
export default {
data() {
return {}
},
methods: {
handleClick() {
this.$emit("increment-counter");
}
}
}
Receiving data from the component
When your component broadcasts data, the parent component still needs to receive it somehow. You can do it like handling any other event, by using the v-on directive. Event type you broadcast in your emit, is the type you are using in the directive.
<!--Parent component-->
<template>
<div>
<div>Number of clicks: {{counter}}</div>
<CounterButton v-on:increment-counter="increment"></CounterButton>
</div>
</template>
<script>
import CounterButton from './CounterButton.vue';
export default {
components: {CounterButton},
data() {
return {
counter: 0
}
},
methods: {
increment() {
this.counter++;
}
}
}
</script>
Declaring events
When building components that broadcast events, it is a good practice to declare events the component broadcasts. This is done by using the emits property of the component.
export default {
emits: ["increment-counter"],
data() {
return {}
},
methods: {
handleClick() {
this.$emit("increment-counter");
}
}
}
The code used in this article can be found in my GitHub repository.
For more, you can follow me on Twitter, LinkedIn, GitHub, or Instagram.
Top comments (0)