Component-Based Development Basics
🎯 Introduction
This article introduces component-based development, the structure of Vue single-file components, and how to create and register components. You will also learn how components communicate with parents, children, and more distant descendants, how slots work, and how to use dynamic components. These skills help you organize frontend projects more clearly and reuse more code.
🧩 Component-Based Development Basics
Component-based development breaks a page into independent, reusable building blocks. Components are a core feature of Vue. Single-file components (.vue files) bring templates, logic, and styles together in one file, simplifying development and maintenance.
🐱🏍 Single-File Components (.vue Structure)
Single-file components are a format used in the Vue ecosystem, with the .vue extension. They combine three essential parts of a component:
<template>: defines the component's HTML structure<script>: contains the component's logic<style>: defines the component's styles
Here is a minimal .vue component:
<template>
<div class="hello">
<h1>{{ message }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
message: 'Welcome to component-based development!',
};
},
};
</script>
<style scoped>
.hello {
color: #42b983;
font-weight: bold;
}
</style>
<style scoped> limits styles to the current component, preventing them from affecting the rest of the application.This structure gives the component a clear responsibility and keeps its logic and styles together for easier maintenance and reuse.
🧱 Creating and Registering Components
After creating a component, register it so that a parent component can use it. Vue supports local registration and global registration.
Local Registration
Import and register the component in the parent component's <script> block:
<script>
import HelloWorld from './HelloWorld.vue';
export default {
components: {
HelloWorld,
},
};
</script>
You can then use <HelloWorld /> in the template.
Global Registration
Register the component in the entry file, such as main.js:
import Vue from 'vue';
import HelloWorld from './HelloWorld.vue';
Vue.component('HelloWorld', HelloWorld);
Any component can then use <HelloWorld /> directly.
💬 Component Communication
Components need to exchange information. The main communication patterns in Vue are:
Passing Data from Parent to Child: props
Child components receive data from their parents through props.
Parent component:
<template>
<ChildComponent :title="pageTitle" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
data() {
return {
pageTitle: 'A title from the parent component',
};
},
};
</script>
Child component, ChildComponent.vue:
<template>
<h2>{{ title }}</h2>
</template>
<script>
export default {
props: ['title'],
};
</script>
Sending Messages from Child to Parent: $emit
The child emits an event with $emit, and the parent listens for it.
Child component:
<template>
<button @click="$emit('alert', 'The button was clicked')">Click me</button>
</template>
Parent component:
<template>
<ChildComponent @alert="handleAlert" />
</template>
<script>
export default {
methods: {
handleAlert(message) {
alert(message);
},
},
};
</script>
props follow a one-way data flow from parent to child. Children should not modify props directly, which helps keep data consistent.🌉 Communicating Across Component Levels: Provide & Inject
When components are deeply nested, passing data from a parent to a grandchild or a more distant descendant through props can become cumbersome. Vue provides provide and inject to pass values across component levels.
Parent component:
<script>
export default {
provide() {
return {
color: 'red',
};
},
};
</script>
Grandchild or a more deeply nested component:
<script>
export default {
inject: ['color'],
mounted() {
console.log('Injected color:', this.color); // red
},
};
</script>
provide/inject bindings are not reactive by default. If you need reactive data, use Vue.observable alongside them or adopt a state management solution.🪟 Slots (Default and Named Slots)
Slots let a parent pass content into specific locations in a child component, making components more flexible.
Default Slots
Child component template:
<template>
<div class="wrapper">
<slot></slot>
</div>
</template>
Parent component:
<template>
<ChildComponent>
<p>This is the default slot content</p>
</ChildComponent>
</template>
Named Slots
Child component:
<template>
<header>
<slot name="header">Default header</slot>
</header>
<main>
<slot>Default content</slot>
</main>
<footer>
<slot name="footer">Default footer</slot>
</footer>
</template>
Parent component:
<template>
<ChildComponent>
<template v-slot:header>
<h1>Custom header</h1>
</template>
<template v-slot:footer>
<small>Custom footer</small>
</template>
Default slot content
</ChildComponent>
</template>
🔄 Using Dynamic Components (the <component> Element)
Use the <component> element to dynamically render different components based on data.
<template>
<component :is="currentComponent" />
<button @click="toggle">Switch component</button>
</template>
<script>
import CompA from './CompA.vue';
import CompB from './CompB.vue';
export default {
components: { CompA, CompB },
data() {
return {
currentComponent: 'CompA',
};
},
methods: {
toggle() {
this.currentComponent = this.currentComponent === 'CompA' ? 'CompB' : 'CompA';
},
},
};
</script>
When currentComponent changes to CompB, Vue displays the CompB component.
❓ Questions and Answers
Q1: Why should child components avoid modifying props directly?
Props follow a one-way data flow. Modifying them in a child interferes with the parent's source of truth and can cause inconsistent data. Instead, emit an event to ask the parent to make the change.
Q2: Is data passed through provide/inject reactive?
The bindings are not reactive by default. Use Vue.observable or another reactivity solution when reactive behavior is needed.
Q3: When are dynamic components with <component> useful?
They are useful for switching content, such as tabs, multi-step flows, or different content within a dialog.
🧪 Exercises
Exercise 1: Create a Dialog with Default and Named Slots
Write a Dialog.vue component with:
- A named
titleslot for the dialog title - A default slot for the dialog content
- A named
footerslot for the buttons at the bottom
Use this component in a parent and pass content to each slot.
Exercise 2: Build a Component That Switches Between Lists
Write a component with two child components, ListA.vue and ListB.vue, and switch the displayed list when a button is clicked.
<template>
<div>
<button @click="toggle">Switch list</button>
<component :is="currentList" />
</div>
</template>
<script>
import ListA from './ListA.vue';
import ListB from './ListB.vue';
export default {
components: { ListA, ListB },
data() {
return {
currentList: 'ListA',
};
},
methods: {
toggle() {
// TODO
},
},
};
</script>
🎉 You now understand single-file component structure, component communication, slots, and dynamic components. Keep practicing to use components effectively when building complex pages!
