Vue Component Basics
Components are reusable Vue instances with a name. We can use a component as a custom element within a Vue root instance created through new Vue.
What are Components?
Components allow us to divide the UI into independent, reusable parts, and think about each part independently. In practical applications, an application's user interface can usually be abstracted as a component tree.
For example, you might have components for the header, sidebar, content area, etc., and each component might contain other components like navigation links or blog posts.
A Simple Example
Let's create a simple button component. This component can track how many times it has been clicked.
ButtonCounter.vue
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
<template>
<button @click="count++">
You clicked me {{ count }} times.
</button>
</template>This file defines an independent Vue component. It encapsulates its own:
- Logic (
<script setup>): A reactive variablecount. - View (
<template>): A button that displayscountand listens to click events. - Style (
<style>) (not included in this example): The component's own CSS.
Using Components
To use this child component, we need to import it in the parent component and register it.
App.vue (Parent Component)
<script setup>
// 1. Import your component
import ButtonCounter from './components/ButtonCounter.vue'
</script>
<template>
<h1>Here are many child components!</h1>
<!-- 2. Use the component -->
<ButtonCounter />
<ButtonCounter />
<ButtonCounter />
</template>In this example:
- We imported the component we created from
./components/ButtonCounter.vue. - In the parent component's
<template>, we can use<ButtonCounter />just like a normal HTML tag.
When you render this parent component, you'll see three independent buttons. Each button maintains its own count state. Clicking one of the buttons will only affect that button's own count value and won't affect the other buttons.
Component Reuse
Components can be reused unlimited times. Each time you use a component, you create a new instance. Each instance manages its own data, so they are independent of each other.
<template>
<ButtonCounter />
<ButtonCounter />
<ButtonCounter />
</template>The code above will render three <ButtonCounter> component instances.
Organizing Components
Typically, an application is organized as a nested component tree:
App (Root Component)
├─ Layout
│ ├─ Header
│ │ └─ NavigationLinks
│ ├─ Sidebar
│ │ └─ UserProfile
│ └─ Content
│ └─ BlogPost
└─ FooterTo let Vue know where to render these components, we need to properly place them in templates. A good practice is to organize component files in the src/components directory and group them by functionality.
By splitting complex UI into independent, manageable components, we greatly improve code maintainability and reusability.