Маршрутизация и состояние: Router и Pinia

Vue Router: настройка

// router/index.js
import { createRouter, createWebHistory } from 'vue-router';

const routes = [
  { path: '/', name: 'home', component: () => import('@/views/HomeView.vue') },
  {
    path: '/products',
    name: 'products',
    component: () => import('@/views/ProductsView.vue'),
  },
  {
    path: '/products/:id',
    name: 'product',
    component: () => import('@/views/ProductView.vue'),
    props: true,                     // :id придёт как пропс, а не через route
  },
  {
    path: '/dashboard',
    component: () => import('@/layouts/DashboardLayout.vue'),
    meta: { requiresAuth: true },
    children: [                      // вложенные маршруты
      { path: '', name: 'dashboard', component: () => import('@/views/Overview.vue') },
      { path: 'settings', component: () => import('@/views/Settings.vue') },
    ],
  },
  { path: '/:pathMatch(.*)*', component: () => import('@/views/NotFound.vue') },
];

export const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, saved) {
    if (saved) return saved;                       // при «назад» — вернуть позицию
    if (to.hash) return { el: to.hash, top: 80 };
    return { top: 0 };
  },
});
💡 Совет
Ленивая загрузка через () => import(...) должна быть по умолчанию для всех маршрутов, кроме главной. Каждый маршрут попадёт в свой чанк — при первой загрузке пользователь скачает только то, что видит.

Навигация

<script setup>
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();   // для действий
const route = useRoute();     // для чтения текущего маршрута

const id = computed(() => route.params.id);
const page = computed(() => Number(route.query.page ?? 1));

function goToProduct(id) {
  router.push({ name: 'product', params: { id } });
}

function applyFilter(category) {
  router.push({ query: { ...route.query, category, page: 1 } });
}
</script>

<template>
  <RouterLink :to="{ name: 'product', params: { id: 42 } }">Товар</RouterLink>
  <RouterLink to="/about" active-class="text-white">О нас</RouterLink>

  <RouterView v-slot="{ Component }">
    <Transition name="fade" mode="out-in">
      <component :is="Component" />
    </Transition>
  </RouterView>
</template>

Защита маршрутов

router.beforeEach(async (to) => {
  const auth = useAuthStore();

  if (!auth.checked) await auth.fetchUser();     // восстановление сессии

  if (to.meta.requiresAuth && !auth.isAuthenticated) {
    return { name: 'login', query: { redirect: to.fullPath } };
  }

  if (to.meta.role && auth.user?.role !== to.meta.role) {
    return { name: 'forbidden' };
  }

  return true;                                    // пропустить
});

router.afterEach((to) => {
  document.title = to.meta.title ? `${to.meta.title} — Магазин` : 'Магазин';
});
⚠ Грабли
Навигационная защита — это UX, а не безопасность. Любой может открыть DevTools и вызвать нужный запрос напрямую. Права всегда проверяются на сервере; фронтенд лишь не показывает то, что всё равно не сработает.

Pinia: хранилище

// stores/cart.js
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useCartStore = defineStore('cart', () => {
  // state
  const items = ref([]);
  const promoCode = ref(null);

  // getters
  const count = computed(() => items.value.reduce((s, i) => s + i.qty, 0));
  const subtotal = computed(() =>
    items.value.reduce((s, i) => s + i.price * i.qty, 0)
  );
  const discount = computed(() => promoCode.value ? subtotal.value * 0.1 : 0);
  const total = computed(() => subtotal.value - discount.value);
  const isEmpty = computed(() => items.value.length === 0);

  // actions
  function add(product, qty = 1) {
    const existing = items.value.find(i => i.id === product.id);
    if (existing) existing.qty += qty;
    else items.value.push({ ...product, qty });
  }

  function remove(id) {
    items.value = items.value.filter(i => i.id !== id);
  }

  function setQty(id, qty) {
    const item = items.value.find(i => i.id === id);
    if (!item) return;
    if (qty <= 0) remove(id);
    else item.qty = qty;
  }

  async function checkout() {
    const order = await api.post('/orders', { items: items.value });
    items.value = [];
    return order;
  }

  return { items, promoCode, count, subtotal, discount, total, isEmpty,
           add, remove, setQty, checkout };
});
<script setup>
import { storeToRefs } from 'pinia';
import { useCartStore } from '@/stores/cart';

const cart = useCartStore();

// Реактивность при деструктуризации сохраняет только storeToRefs
const { items, total, count } = storeToRefs(cart);
// Действия можно доставать напрямую — они не реактивны
const { add, remove } = cart;
</script>

<template>
  <p>В корзине: {{ count }} на {{ total }} ₽</p>
  <button @click="add(product)">Купить</button>
</template>
⚠ Грабли
Обычная деструктуризация const { total } = cart оборвёт реактивность — значение «застынет». Для состояния и геттеров всегда storeToRefs. Это ошибка номер один при работе с Pinia.

Хранилище авторизации

// stores/auth.js
export const useAuthStore = defineStore('auth', () => {
  const user = ref(null);
  const checked = ref(false);

  const isAuthenticated = computed(() => user.value !== null);
  const isAdmin = computed(() => user.value?.role === 'admin');

  async function login(credentials) {
    const { data } = await api.post('/auth/login', credentials);
    user.value = data.user;
  }

  async function fetchUser() {
    try {
      const { data } = await api.get('/auth/me');
      user.value = data;
    } catch {
      user.value = null;
    } finally {
      checked.value = true;
    }
  }

  async function logout() {
    await api.post('/auth/logout');
    user.value = null;
    router.push({ name: 'login' });
  }

  return { user, checked, isAuthenticated, isAdmin, login, fetchUser, logout };
});

Что класть в хранилище

В Pinia:
• пользователь и права
• корзина, избранное
• настройки интерфейса (тема, язык, свёрнутый сайдбар)
• данные, нужные нескольким несвязанным экранам

НЕ в Pinia:
• состояние формы — оно живёт с компонентом
• данные одного экрана, которые загружаются при входе на него
• кеш серверных ответов — для этого есть TanStack Query для Vue
  (ревалидация, дедупликация, повторы — писать это в сторе руками накладно)
⚖ Что когда применять
Начинайте без глобального состояния: пропсы, события, composables. Заводите стор, когда одни и те же данные нужны в несвязанных частях приложения или когда прокидывание пропсов стало болезненным. Преждевременно вынесенное в стор состояние формы — типичная ошибка, из-за которой компонент перестаёт быть переиспользуемым.

Практика

Задание 1

Спроектируй маршрутизацию интернет-магазина с вложенными макетами, ленивой загрузкой, защитой админки и восстановлением сессии. Добавь заголовки страниц и обработку 404.
Решение
// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import { useAuthStore } from '@/stores/auth';

const routes = [
  {
    path: '/',
    component: () => import('@/layouts/ShopLayout.vue'),
    children: [
      { path: '', name: 'home',
        component: () => import('@/views/HomeView.vue'),
        meta: { title: 'Главная' } },

      { path: 'catalog/:category?', name: 'catalog',
        component: () => import('@/views/CatalogView.vue'),
        props: true,
        meta: { title: 'Каталог' } },

      { path: 'products/:id', name: 'product',
        component: () => import('@/views/ProductView.vue'),
        props: route => ({ id: Number(route.params.id) }),
        meta: { title: 'Товар' } },

      { path: 'cart', name: 'cart',
        component: () => import('@/views/CartView.vue'),
        meta: { title: 'Корзина' } },

      { path: 'checkout', name: 'checkout',
        component: () => import('@/views/CheckoutView.vue'),
        meta: { title: 'Оформление', requiresAuth: true } },
    ],
  },

  {
    path: '/account',
    component: () => import('@/layouts/AccountLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      { path: '', name: 'account',
        component: () => import('@/views/account/ProfileView.vue'),
        meta: { title: 'Профиль' } },
      { path: 'orders', name: 'orders',
        component: () => import('@/views/account/OrdersView.vue'),
        meta: { title: 'Мои заказы' } },
      { path: 'orders/:id', name: 'order',
        component: () => import('@/views/account/OrderView.vue'),
        props: true },
    ],
  },

  {
    path: '/admin',
    component: () => import('@/layouts/AdminLayout.vue'),
    meta: { requiresAuth: true, roles: ['admin', 'manager'] },
    children: [
      { path: '', name: 'admin',
        component: () => import('@/views/admin/DashboardView.vue'),
        meta: { title: 'Панель управления' } },
      { path: 'products', name: 'admin-products',
        component: () => import('@/views/admin/ProductsView.vue') },
      { path: 'users', name: 'admin-users',
        component: () => import('@/views/admin/UsersView.vue'),
        meta: { roles: ['admin'] } },     // только админ, без менеджера
    ],
  },

  { path: '/login', name: 'login',
    component: () => import('@/views/LoginView.vue'),
    meta: { title: 'Вход', guestOnly: true } },

  { path: '/403', name: 'forbidden',
    component: () => import('@/views/ForbiddenView.vue') },

  { path: '/:pathMatch(.*)*', name: 'not-found',
    component: () => import('@/views/NotFoundView.vue'),
    meta: { title: 'Страница не найдена' } },
];

export const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) return savedPosition;        // кнопка «назад»
    if (to.hash) return { el: to.hash, top: 80, behavior: 'smooth' };
    if (to.path === from.path) return {};           // смена только query — не скроллим
    return { top: 0 };
  },
});

// Защита маршрутов
router.beforeEach(async (to) => {
  const auth = useAuthStore();

  // Восстановление сессии при первом заходе или обновлении страницы
  if (!auth.checked) {
    await auth.fetchUser();
  }

  if (to.meta.guestOnly && auth.isAuthenticated) {
    return { name: 'home' };
  }

  if (to.meta.requiresAuth && !auth.isAuthenticated) {
    return { name: 'login', query: { redirect: to.fullPath } };
  }

  // Роли ищем по всей цепочке: правило может быть на родителе
  const required = to.matched
    .map(r => r.meta.roles)
    .filter(Boolean)
    .flat();

  if (required.length && !required.includes(auth.user?.role)) {
    return { name: 'forbidden' };
  }

  return true;
});

router.afterEach((to) => {
  const title = to.meta.title;
  document.title = title ? `${title} — Магазин` : 'Магазин';
});

// Обработка сбоя ленивой загрузки после деплоя новой версии
router.onError((error, to) => {
  if (/Failed to fetch dynamically imported module/i.test(error.message)) {
    window.location.href = to.fullPath;   // жёсткая перезагрузка на новую сборку
  }
});

router.onError с перезагрузкой — то, о чём узнают после первого продакшен-инцидента: при выкладке новой версии старые чанки исчезают, и у пользователей с открытой вкладкой навигация начинает падать.

Задание 2

Напиши стор Pinia для корзины: добавление с учётом остатков, промокод, синхронизация с localStorage и сервером, обработка ошибок оформления. Покажи корректное использование в компоненте.
<!-- Использование в компоненте -->
<script setup>
import { storeToRefs } from 'pinia';
import { onMounted } from 'vue';
import { useCartStore } from '@/stores/cart';

const cart = useCartStore();

// Состояние и геттеры — только через storeToRefs
const { items, total, count, isEmpty, syncing, lastError } = storeToRefs(cart);
// Действия можно брать напрямую
const { add, remove, setQty, checkout } = cart;

onMounted(() => cart.revalidate());   // сверяем цены при открытии корзины
</script>

<template>
  <p v-if="lastError" role="alert">{{ lastError }}</p>
  <p v-if="isEmpty">Корзина пуста</p>
  <ul v-else>
    <li v-for="item in items" :key="item.id">
      {{ item.title }}
      <input type="number" :value="item.qty" :max="item.maxQty"
             @input="setQty(item.id, Number($event.target.value))">
      <button @click="remove(item.id)">Убрать</button>
    </li>
  </ul>
  <p>Итого: {{ total }} ₽</p>
  <button :disabled="isEmpty || syncing" @click="checkout(form)">Оформить</button>
</template>
Решение
// stores/cart.js
import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';
import { cartApi } from '@/api/cart';

const STORAGE_KEY = 'cart-v1';

export const useCartStore = defineStore('cart', () => {
  /* --- state --- */
  const items = ref([]);          // [{ id, title, price, qty, maxQty, image }]
  const promo = ref(null);        // { code, discountPercent }
  const syncing = ref(false);
  const lastError = ref(null);

  /* --- getters --- */
  const count = computed(() => items.value.reduce((s, i) => s + i.qty, 0));

  const subtotal = computed(() =>
    items.value.reduce((s, i) => s + i.price * i.qty, 0)
  );

  const discount = computed(() =>
    promo.value ? Math.round(subtotal.value * promo.value.discountPercent / 100) : 0
  );

  const delivery = computed(() => subtotal.value >= 5000 ? 0 : 400);

  const total = computed(() => subtotal.value - discount.value + delivery.value);

  const isEmpty = computed(() => items.value.length === 0);

  const hasIssues = computed(() =>
    items.value.some(i => i.maxQty !== undefined && i.qty > i.maxQty)
  );

  /* --- actions --- */
  function add(product, qty = 1) {
    const existing = items.value.find(i => i.id === product.id);
    const limit = product.maxQty ?? Infinity;

    if (existing) {
      existing.qty = Math.min(existing.qty + qty, limit);
    } else {
      items.value.push({
        id: product.id,
        title: product.title,
        price: product.price,
        image: product.image,
        maxQty: product.maxQty,
        qty: Math.min(qty, limit),
      });
    }
  }

  function setQty(id, qty) {
    const item = items.value.find(i => i.id === id);
    if (!item) return;
    if (qty <= 0) { remove(id); return; }
    item.qty = Math.min(qty, item.maxQty ?? Infinity);
  }

  function remove(id) {
    items.value = items.value.filter(i => i.id !== id);
  }

  function clear() {
    items.value = [];
    promo.value = null;
  }

  async function applyPromo(code) {
    lastError.value = null;
    try {
      const result = await cartApi.checkPromo(code, subtotal.value);
      promo.value = { code, discountPercent: result.discountPercent };
      return true;
    } catch (e) {
      lastError.value = e.response?.data?.message ?? 'Промокод не найден';
      return false;
    }
  }

  // Сверка цен и остатков с сервером — цены могли измениться
  async function revalidate() {
    if (isEmpty.value) return;
    syncing.value = true;
    try {
      const fresh = await cartApi.validate(
        items.value.map(i => ({ id: i.id, qty: i.qty }))
      );
      items.value = items.value
        .map(i => {
          const s = fresh.find(f => f.id === i.id);
          if (!s || !s.available) return null;
          return { ...i, price: s.price, maxQty: s.maxQty,
                   qty: Math.min(i.qty, s.maxQty) };
        })
        .filter(Boolean);
    } finally {
      syncing.value = false;
    }
  }

  async function checkout(deliveryInfo) {
    lastError.value = null;
    syncing.value = true;
    try {
      const order = await cartApi.createOrder({
        items: items.value.map(i => ({ productId: i.id, qty: i.qty })),
        promoCode: promo.value?.code,
        delivery: deliveryInfo,
      });
      clear();
      return order;
    } catch (e) {
      // 409 — что-то раскупили, пока пользователь оформлял
      if (e.response?.status === 409) {
        await revalidate();
        lastError.value = 'Часть товаров разобрали. Проверьте корзину.';
      } else {
        lastError.value = e.response?.data?.message ?? 'Не удалось оформить заказ';
      }
      throw e;
    } finally {
      syncing.value = false;
    }
  }

  /* --- сохранение между сессиями --- */
  function restore() {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (raw) {
        const saved = JSON.parse(raw);
        items.value = saved.items ?? [];
        promo.value = saved.promo ?? null;
      }
    } catch {
      localStorage.removeItem(STORAGE_KEY);
    }
  }

  watch([items, promo], () => {
    localStorage.setItem(STORAGE_KEY,
      JSON.stringify({ items: items.value, promo: promo.value }));
  }, { deep: true });

  return {
    items, promo, syncing, lastError,
    count, subtotal, discount, delivery, total, isEmpty, hasIssues,
    add, setQty, remove, clear, applyPromo, revalidate, checkout, restore,
  };
});

revalidate при открытии корзины — то, что отличает учебный пример от рабочего: между добавлением товара и оформлением могут пройти дни, за которые изменятся и цена, и остаток.