We're making great progress. We now have a component that can accept input, be registered globally or locally, has scoped styles, validation, and more. Now we need to give it the ability to fire events back to its parent component to communicate whenever the FancyButton button is clicked, this is done by editing the code for the $emit event:
<template>
<button
@click.prevent="clicked">
{{buttonText}}
</button>
</template>
<script>
export default {
props: {
buttonText: {
type: String,
default: () => {
return "Fancy Button!"
},
required: true,
validator: value => value.length > 3
}
},
methods: {
clicked() {
this.$emit('buttonClicked');
}
}
}
</script>
In our example, we've attached the clicked function to the click event of the button, meaning that whenever it is selected we're emitting the buttonClicked event. We can then listen for this event within our App.vue file, where we add our element to the DOM:
<template>
<fancy-button
@buttonClicked="eventListener()"
button-text="Click
me!">
</fancy-button>
</template>
<script>
import FancyButton from './components/FancyButton.vue';
export default {
components: {
'fancy-button': FancyButton
},
methods: {
eventListener() {
console.log("The button was clicked from the child component!");
}
}
}
</script>
<style>
</style>
Notice how at this point we're using @buttonClicked="eventListener()". This uses the v-on event to call the eventListener() function any time the event is emitted, subsequently logging the message to the console. We've now demonstrated the ability to send and receive events between two components.