Vue — Components
Defining components
<!-- Button.vue -->
<template>
<button class="btn" :class="type">
<slot></slot>
</button>
</template>
<script>
export default {
name: 'MyButton',
props: {
type: {
type: String,
default: 'primary'
}
}
}
</script>
<style scoped>
.btn {
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.primary { background: #3498db; color: white; }
.secondary { background: #2ecc71; color: white; }
.danger { background: #e74c3c; color: white; }
</style>
Using components
<template>
<div>
<MyButton type="primary">Click Me</MyButton>
<MyButton type="secondary">Cancel</MyButton>
</div>
</template>
<script>
import MyButton from './MyButton.vue'
export default {
components: {
MyButton
}
}
</script>
Component registration
// Local registration
import MyButton from './MyButton.vue'
export default {
components: { MyButton }
}
// Global registration
app.component('MyButton', MyButton)
Props
<script>
export default {
props: {
title: String,
count: Number,
isActive: Boolean,
items: Array,
user: Object,
size: {
type: String,
default: 'medium',
validator: (val) => ['small', 'medium', 'large'].includes(val)
}
}
}
</script>
Events
<template>
<button @click="$emit('click', $event)">Click</button>
</template>
<script>
export default {
emits: ['click']
}
</script>
Slots
<template>
<div class="card">
<header><slot name="header"></slot></header>
<main><slot></slot></main>
<footer><slot name="footer"></slot></footer>
</div>
</template>
Mini Practice
- Create a reusable button component
- Pass props and handle events
- Use named slots
- Add scoped styles
Up Next
Continue with Props - Passing data to child components.
Related Topics
Frequently Asked Questions about Components
What is Components in Vue?
Components 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 Components?
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 Components.
Why is Components important in Vue?
Components is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.