Vue — Events
Emitting events
<!-- Child component -->
<template>
<button @click="$emit('click')">Click me</button>
</template>
<script>
export default {
emits: ['click']
}
</script>
Parent listener
<template>
<ChildButton @click="handleClick" />
</template>
<script>
export default {
methods: {
handleClick() {
console.log('Button clicked!')
}
}
}
</script>
Passing data with events
<!-- Child -->
<template>
<button @click="$emit('select', item)">Select</button>
</template>
<script>
export default {
props: ['item'],
emits: ['select']
}
</script>
<!-- Parent -->
<template>
<ChildButton @select="handleSelect" />
</template>
<script>
export default {
methods: {
handleSelect(item) {
console.log('Selected:', item)
}
}
}
</script>
Event modifiers
<!-- .native modifier for component events -->
<ChildButton @click.native="handleClick" />
Custom events with emit
<template>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
</template>
<script>
export default {
props: ['modelValue'],
emits: ['update:modelValue']
}
</script>
Multiple events
<template>
<button @click="$emit('click'); $emit('track', 'button-click')">Click</button>
</template>
Mini Practice
- Emit a simple event
- Pass data with events
- Use custom v-model
- Handle multiple emitted events
Up Next
Continue with Slots - Content distribution.
Related Topics
Frequently Asked Questions about Events
What is Events in Vue?
Events is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Events?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Events.
Why is Events important in Vue?
Events is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.