In Vue, events play a crucial role in facilitating communication between components, allowing them to interact and share information.
There are primarily two types of events in Vue.js:
DOM Events
Custom Events
DOM events are standard events triggered by user interactions with the browser, such as "clicks", "keypresses", "mouse movements" etc.
Vue provides the 'v-on' directive (or its shorthand @) to listen to DOM events and execute methods or expressions in response to those events.
<button @click="handleOnClick"> Click me </button>
Note: the "handleOnClick" method will be invoked when the button is clicked.
<template> <h1>Greeting Value: {{ inputValue }}</h1> <input type="text" @input="handleInputChange" v-model="inputValue"> </template> <script> export default { name: "HelloWorld", data() { return { inputValue: "Hi" }; }, methods: { handleInputChange(event) { this.inputValue = event.target.value; }, }, }; </script>
The input event is invoked whenever the input value changes.
<input type="text" @change="handleInputChange" v-model="inputValue">
<!-- handleOnSubmit will get Execute when the Enter key is pressed --> <input @keyup.enter="handleOnSubmit" />
The change event is invoked when the input field loses focus and its value has changed since it gained focus.
<template> <input type="text" @keyup="handleKeyUp"> <input type="text" @keypress="handleKeyPress"> <input type="text" @keydown="handleKeyDown"> </template> <script> export default { components: { ChildComponent }, methods: { handleKeyUp() { // Handle key Up Pressed event }, handleKeyPress() { // Handle key Pressed event }, handleKeyDown() { // Handle key Down Pressed event } } } </script>
<!-- ChildComponent.vue --> <template> <button @click="handleOnClick"> Click me </button> </template> <script> export default { methods: { handleOnClick() { this.$emit('custom-event', /* optional payload */); } } } </script>
<!-- ParentComponent.vue --> <template> <ChildComponent @custom-event="handleCustomEvent" /> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { handleCustomEvent() { // Handle the custom event } } } </script>
Vue.js provides key modifiers to listen for specific key events.
These events are invoked when a key is pressed, released, or pressed and released, respectively.
Custom events are events emitted by child components to notify their parent components about specific occurrences or changes.
Vue provides the "$emit" method to emit custom events from child components, and the parent components can listen to these events using "v-on" directive.
when the button in the child component is "clicked", it "emits" a custom event named "custom-event".
The parent component listens to this event using "v-on" directive and calls the "handleCustomEvent" method in response.