Emitting Events in Vue
As you already know, data flows from parent components to child components. Let's now see how child components can communicate with parent components. This is done by emitting events. Let's see it in practice.
Let there be some method in the parent component:
methods: {
func() {
alert('xxx');
}
}
Let's pass this method as a parameter to the child component:
<template>
<User @show="func" />
</template>
Let's register the emitted event in the emits
setting:
export default {
emits: ['show'],
data() {
return {
}
}
}
Let's now make a button in the child component that will handle clicks on it:
<template>
<button @click="handle">btn</button>
</template>
Let's make a click handler:
methods: {
handle() {
}
}
Now let's make the parent function be called in the click handler. To do this, we emit an event using the $emit
function, specifying the name of the emitted event as its parameter:
methods: {
handle() {
this.$emit('show');
}
}
Pass two functions to the child component. Make two buttons in the child component, each of which will call one of the passed functions.