Vue.js 3 Essentials: Lifecycle Hooks, State Management & More Explained Simply
đ Picture this: You're building your first Vue.js app, and everything seems magicalâuntil your component doesnât update when it should, your state feels chaotic, or API calls fire at the wrong time. Suddenly, Vue.js feels less like a superpower and more like a puzzle.
Sound familiar? Donât worry!
In this guide, weâll break down Vue.js essentialsâlifecycle hooks, reactive state, component communication, routing, form validation, Pinia (Vuexâs modern replacement), and API callsâin a way thatâs easy, practical, and beginner-friendly.
By the end, youâll confidently control your appâs behavior like a pro. Letâs dive in!
đ 1. Lifecycle Hooks: Controlling Your Componentâs Life
Every Vue component has a lifecycleâitâs born (mounted), updates (when data changes), and eventually gets destroyed (unmounted). Lifecycle hooks let you run code at these key moments.
Key Lifecycle Hooks
| Vue 3 Hooks | When It Runs | Use Case |
|---|---|---|
onMounted |
After component is added to the DOM | Fetching API data, setting up event listeners |
onUpdated |
After component updates (data changes) | Debugging re-renders, DOM manipulations |
onUnmounted |
Before component is removed | Cleaning up timers, subscriptions |
Example: Fetching Data on Mount
<script setup>
import { onMounted } from 'vue';
onMounted(() => {
console.log('Component is ready!');
fetchData(); // Load data when component appears
});
</script>
đĄ Pro Tip: Avoid heavy logic in onUpdatedâit runs on every re-render and can cause performance issues!
đĄ 2. Reactive State: ref() vs. reactive()
Vueâs reactivity system makes your UI update automatically when data changes.
ref()
- Best for primitive values (strings, numbers, booleans).
- Access/modify with
.value.
import { ref } from 'vue';
const count = ref(0); // count.value = 1
reactive()
- Best for objects/arrays.
- No
.valueneeded.
import { reactive } from 'vue';
const user = reactive({ name: 'Alice' }); // user.name = 'Bob'
đ Which to use?
- Use
reffor simple values. - Use
reactivefor complex objects.
đŁïž 3. Component Communication
Components need to talk! Hereâs how:
| Method | Use Case |
|---|---|
| Props | Parent â Child data flow |
| Emits | Child â Parent events |
| Provide/Inject | Grandparent â Grandchild (avoid prop drilling) |
| Slots | Dynamic content inside components |
Example: Parent â Child via Props
<!-- Parent -->
<ChildComponent :message="hello" />
<!-- Child -->
<script setup>
defineProps(['message']); // Access via props.message
</script>
đ§ 4. Routing with vue-router
Need multiple pages? vue-router has you covered.
Key Features
<router-link>for navigation (like<a>but faster).useRoute()to access current route (params, query).useRouter()to programmatically navigate (router.push('/home')).
Example: Basic Navigation
import { useRouter } from 'vue-router';
const router = useRouter();
function goHome() {
router.push('/'); // Redirect to home
}
đ 5. Form Validation (VeeValidate, Vuelidate, or Custom)
Forms are trickyâvalidation shouldnât be!
Option 1: VeeValidate (Recommended)
<template>
<Form @submit="onSubmit">
<Field name="email" rules="required|email" />
<ErrorMessage name="email" />
</Form>
</template>
Option 2: Custom Validation
const email = ref('');
const errors = ref({});
function validate() {
if (!email.value) errors.value.email = 'Required!';
}
đȘ 6. State Management with Pinia (Vuex Replacement)
For global state (like user auth, shopping cart), Pinia is the modern choice.
Example: Creating a Store
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() { this.count++; }
}
});
Using the Store in Components
import { useCounterStore } from '@/stores/counter';
const counter = useCounterStore();
counter.increment(); // Updates globally!
đ 7. API Calls with Axios
Fetching data? Axios is your friend.
Best Practice: Call APIs in onMounted
import { onMounted, ref } from 'vue';
import axios from 'axios';
const posts = ref([]);
onMounted(async () => {
const response = await axios.get('https://api.example.com/posts');
posts.value = response.data;
});
đ Tip: Handle errors with try/catch!
đ„ Final Thoughts & Next Steps
Now youâve got the essential Vue.js toolkit:
â
Control component timing with lifecycle hooks.
â
Manage state reactively with ref()/reactive().
â
Communicate between components without chaos.
â
Add routing, forms, global state, and API calls like a pro.
Your challenge: Pick one concept (like Pinia or onMounted) and implement it in a project today!
â FAQs
Q1: Should I use Vuex or Pinia?
A: Pinia! Itâs the official recommendation, simpler, and works with Vue 3.
Q2: When should I use ref vs. reactive?
A: Use ref for single values (numbers, strings) and reactive for objects/arrays.
Q3: Is Axios better than fetch()?
A: Yes! Axios has better error handling and request/response interceptors.
Whatâs your biggest Vue.js struggle right now? Letâs discuss in the comments! đđŹ
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
đ Featuresâ Google & GitHub Authenticationâ User Registration & Loginâ Profile/Dashboard Accessâ Secure & Mi...
Flask Blog CMS with Admin Dashboard â Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
đ Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.