Asosiy matnga o'tish
ITIT Interview
Vue.js

Vue Router

Marshrutlar, dinamik parametrlar, ichma-ich marshrutlar, RouterLink va programmatik navigatsiya, navigatsiya guard'lari, lazy loading, history rejimlari.

O'rganildi: 0 / 6
Progress

Sozlash

router/index.ts
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '@/views/HomeView.vue';

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', name: 'home', component: HomeView },
    { path: '/about', name: 'about', component: () => import('@/views/AboutView.vue') },  // lazy
    { path: '/users/:id', name: 'user', component: () => import('@/views/UserView.vue'), props: true },
    {
      path: '/dashboard',
      component: () => import('@/layouts/DashboardLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        { path: '', component: () => import('@/views/DashboardHome.vue') },          // /dashboard
        { path: 'settings', component: () => import('@/views/Settings.vue') },       // /dashboard/settings
      ],
    },
    { path: '/:pathMatch(.*)*', name: 'not-found', component: () => import('@/views/NotFound.vue') },
  ],
  scrollBehavior: () => ({ top: 0 }),
});

export default router;
main.ts
createApp(App).use(router).mount('#app');
App.vue
<template>
  <nav>
    <RouterLink to="/">Bosh sahifa</RouterLink>
    <RouterLink :to="{ name: 'user', params: { id: 42 } }">Profil</RouterLink>
  </nav>
  <RouterView />
</template>

Ichma-ich marshrutlar uchun ota komponentda (masalan, DashboardLayout.vue) ham RouterView bo'ladi.

Parametrlar va query

views/UserView.vue
<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { watch } from 'vue';

const route = useRoute();
const router = useRouter();

// /users/42?tab=posts
route.params.id;     // '42'
route.query.tab;     // 'posts'

// Bir xil komponent qayta ishlatiladi: /users/1 → /users/2 da komponent qayta yaratilmaydi
watch(() => route.params.id, (id) => loadUser(id as string), { immediate: true });

function goBack() {
  router.push({ name: 'home' });
  // router.replace(...)  — tarixga yozmaydi
  // router.back()
}
</script>

props: true bilan parametr prop sifatida keladi va komponent router'ga bog'lanmaydi.

// Global — har bir o'tishdan oldin
router.beforeEach((to, from) => {
  const auth = useAuthStore();
  if (to.meta.requiresAuth && !auth.isLoggedIn) {
    return { name: 'login', query: { redirect: to.fullPath } };   // yo'naltirish
  }
  // hech narsa qaytarmaslik yoki true — davom etish; false — bekor qilish
});

router.afterEach((to) => {
  document.title = (to.meta.title as string) ?? 'Ilova';
});
// Marshrut darajasida
{ path: '/admin', component: Admin, beforeEnter: (to) => isAdmin() || '/403' }
// Komponent ichida
import { onBeforeRouteLeave } from 'vue-router';

onBeforeRouteLeave(() => {
  if (hasUnsavedChanges.value) return confirm("Saqlanmagan o'zgarishlar bor. Chiqasizmi?");
});

Guard'lar faqat UX uchun. Haqiqiy himoya serverda bo'lishi kerak: foydalanuvchi JavaScript'ni o'zgartirib guard'ni chetlab o'tishi mumkin.

History rejimlari

RejimURLServer sozlamasi
createWebHistory/users/42Kerak: barcha yo'llarni index.html ga qaytarish
createWebHashHistory/#/users/42Kerak emas, lekin SEO uchun yomon
createMemoryHistoryURL o'zgarmaydiSSR va testlar

createWebHistory da server sozlanmasa, sahifani yangilaganda 404 chiqadi.

Intervyu savollari

Ushbu sahifada