Vue gives you the flexibility to emit an event with parameters to a function present in the parent component. This is one of the most powerful, yet underrated features of Vue.js. You might come across numerous occasions when you want to perform an action on the child component. However, you want to reflect the effect of this action on the parent component. Here, in this example, I’m going to show you how to do that.
Consider the main (parent) component App.vue:
<template>
<div id="app">
<div>
<label for="age">Age:</label>
<input id="age" type="number" v-model="age" />
</div>
<div id="np-age-modifier-component">
<AgeModifierComponent
@add-age="addToAge"
@multiply-age="multiplyByAge"
/>
</div>
</div>
</template>
<script>
import AgeModifierComponent from "./AgeModifier";
export default {
name: "App",
components: { AgeModifierComponent },
data() {
return {
age: 27,
};
},
methods: {
addToAge(newAge) {
this.age = parseInt(this.age, 10) + parseInt(newAge, 10);
},
multiplyByAge(newAge) {
this.age = parseInt(this.age, 10) * parseInt(newAge, 10);
},
},
};
</script>
Code language: HTML, XML (xml)
And here’s a child component named AgeModifier.vue (imported inside App.vue):
<template>
<div>
<input type="number" v-model="inputValue" />
<button @click="$emit('add-age', inputValue)">Add age</button>
<button @click="$emit('multiply-age', inputValue)">Multiply age</button>
</div>
</template>
<script>
export default {
name: "AgeComponent",
data() {
return {
inputValue: 0,
};
},
};
</script>
Code language: HTML, XML (xml)
In the main component, you’d notice that I’ve imported the child component AgeModifier and have bind two methods addToAge and multiplyByAge to add-age and multiply-age events respectively. Notice how there are no parameters in the calling functions (line 9 and 10). However, the actual function definition are taking parameters (line 28 and 31).
Now if you look at the child component (AgeModifier.vue), there are two event emitters at line numbers 4 and 5. At both these events, I’m passing the event name, ‘add-age’ for instance along with a value inputValue. This inputValue is a local state to the component AgeModifier. However, when you pass it as a parameter to an event emitter, its value gets copied to the original function it is bind with. That is, to the parameters of addToAge(), which is newAge on line 28 of App.vue.
Here’s a working copy of the above example: