Vue Components
Components are reusable pieces of UI that have their own logic and styling. They're the building blocks of Vue applications, allowing you to split your interface into independent, reusable pieces.
Why Components?
Components help you:
- Break down complexity - Divide large apps into manageable pieces
- Reuse code - Write once, use everywhere
- Improve maintainability - Each component has a single responsibility
- Enable collaboration - Different team members can work on different components
Creating Components
With <script setup>, creating a component is as simple as creating a .vue file:
<!-- MyButton.vue -->
<script setup>
const props = defineProps({
label: String
})
</script>
<template>
<button>{{ label }}</button>
</template>
<style scoped>
button {
padding: 0.5rem 1rem;
border-radius: 4px;
}
</style>
Using Components
Import and use components directly in your template:
<script setup>
import MyButton from './MyButton.vue'
</script>
<template>
<MyButton label="Click me!" />
</template>
Note: In Nuxt 3, components in the components/ directory are automatically imported - no need to import them manually!
Component Naming
Follow these conventions:
- PascalCase for component names:
UserProfile.vue,TodoList.vue - Multi-word names to avoid conflicts with HTML elements:
BaseButton.vue, notButton.vue - Descriptive names that indicate what the component does
Scoped Styles
The scoped attribute ensures styles only apply to the current component:
<style scoped>
/* This will only affect this component */
.title {
color: blue;
}
</style>
Challenge
Create a simple card component system:
- Create a
Cardcomponent that:- Accepts a
titleprop (string) - Has a default slot for content
- Displays a title at the top and content below
- Includes some basic styling
- Accepts a
- In
app.vue, use the Card component multiple times with different content
Tip: Remember to use <slot /> to render content passed to your component!
If you get stuck, you can check the solution by clicking the button below.
Components are the foundation of Vue applications. You've now learned the basics - next, we'll explore how components communicate via props and emits!