Vue 3: Advanced Components
Components are the fundamental building blocks of Vue applications. Learning to communicate between them is essential.
Props and Validation
vue
<script setup>
const props = defineProps({
title: {
type: String,
required: true
},
status: {
type: String,
validator: (value) => ['success', 'warning', 'error'].includes(value)
},
count: {
type: Number,
default: 0
}
})
</script>Emit Events
vue
<script setup>
const emit = defineEmits({
update: (payload) => {
if (payload.id && payload.value) {
return true
}
console.warn('Invalid update payload')
return false
}
})
const handleUpdate = () => {
emit('update', { id: 1, value: 'new value' })
}
</script>Provide / Inject
For communication between nested components:
vue
<!-- Parent.vue -->
<script setup>
import { provide } from 'vue'
provide('theme', {
dark: true,
colors: { primary: '#3498db' }
})
</script>
<!-- Child.vue -->
<script setup>
import { inject } from 'vue'
const theme = inject('theme')
</script>Advanced Slots
vue
<!-- Modal.vue -->
<template>
<div class="modal">
<header>
<slot name="header">Default Header</slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>Conclusion
Vue components are powerful and flexible. Mastering props, emits and slots is fundamental for building scalable applications.