🌿 Nested Routes di Vue.js
Nested Routes memungkinkan kamu membuat tampilan yang memiliki struktur halaman bertingkat, seperti dashboard dengan sidebar dan konten dinamis. Fitur ini sangat penting untuk aplikasi skala menengah hingga besar.
📦 1. Contoh Kasus
Misalnya kita punya halaman Dashboard:
/dashboard -> Halaman utama dashboard /dashboard/profile -> Halaman profil /dashboard/settings -> Pengaturan
🧱 2. Struktur Komponen
src/ ├── views/ │ ├── Dashboard.vue │ └── Profile.vue │ └── Settings.vue
🔧 3. Konfigurasi Route
File: router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import Dashboard from '../views/Dashboard.vue';
import Profile from '../views/Profile.vue';
import Settings from '../views/Settings.vue';
Vue.use(Router);
export default new Router({
mode: 'history',
routes: [
{
path: '/dashboard',
component: Dashboard,
children: [
{
path: 'profile',
component: Profile
},
{
path: 'settings',
component: Settings
}
]
}
]
});
🧩 4. Komponen Induk (Dashboard.vue)
Komponen Dashboard.vue
harus menyertakan <router-view>
untuk merender komponen anaknya:
<template>
<div>
<h2>Dashboard</h2>
<ul>
<li><router-link to="/dashboard/profile">Profile</router-link></li>
<li><router-link to="/dashboard/settings">Settings</router-link></li>
</ul>
<router-view />
</div>
</template>
📌 5. Navigasi Nested
Gunakan <router-link>
relatif terhadap parent path:
<router-link to="profile">Profile</router-link> <!-- relatif -->
<router-link to="/dashboard/profile">Profile</router-link> <!-- absolut -->
⚠️ 6. Catatan Penting
-
Path anak tidak perlu diawali
/
. -
<router-view>
di komponen parent wajib ada untuk menampilkan route anak. -
Kamu bisa menambahkan nested di dalam nested lagi (multi-level routing).
✅ 7. Contoh Output
Navigasi ke:
-
/dashboard
→ Menampilkan halaman Dashboard default. -
/dashboard/profile
→ Menampilkan komponen Profile di dalam Dashboard. -
/dashboard/settings
→ Menampilkan komponen Settings di dalam Dashboard.
🎯 Kapan Menggunakan Nested Routes?
-
Dashboard dengan tab atau sidebar
-
Profil pengguna dengan sub-section
-
Admin panel dengan navigasi berjenjang
-
Layout umum dengan konten dinamis per route