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:

  1. Break down complexity - Divide large apps into manageable pieces
  2. Reuse code - Write once, use everywhere
  3. Improve maintainability - Each component has a single responsibility
  4. 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, not Button.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:

  1. Create a Card component that:
    • Accepts a title prop (string)
    • Has a default slot for content
    • Displays a title at the top and content below
    • Includes some basic styling
  2. 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!

Vue Composition API
The Composition API is a set of APIs that allows us to author Vue components using imported functions instead of declaring options. It's an umbrella term that covers:
Props & Emits
Files
Editor
Initializing WebContainer
Mounting files
Installing dependencies
Starting Nuxt server
Waiting for Nuxt to ready
Terminal