Fullstack PHP & Laravel
Trang chủ / Module 11
💚 Module 11 / 19 · 5 ngày 📅 Tuần 8-9 ●●●○ Khó

Vue 3 + Inertia: SPA hiện đại không cần viết API riêng

Stack frontend phổ biến nhất của hệ sinh thái Laravel: Vue 3 Composition API, Inertia (controller trả trang với props, không cần REST cho UI), form và validate lỗi từ Laravel, partial reload, deferred props, prefetch, SSR — và khi nào dùng React thay Vue.

Vue 3Composition APIInertia 2PiniaFormsSSR
📌 Vì sao module này quan trọng

Inertia cho phép xây SPA mượt như React/Vue thuần nhưng giữ routing, auth, validate, phân quyền ở Laravel — không cần thiết kế API riêng cho giao diện của chính mình, giảm một nửa lượng code. Đây là lựa chọn mặc định của các starter kit Laravel và rất phổ biến ở công ty SaaS dùng PHP. Hiểu sâu Vue reactivity và mô hình Inertia là kỹ năng phân biệt fullstack PHP với backend PHP.

🎯 Mục tiêu học tập

  • Dùng Vue 3 Composition API: ref, reactive, computed, watch, composable
  • Hiểu mô hình Inertia: controller trả Inertia::render với props, điều hướng không reload
  • Xử lý form với useForm, lỗi validate 422, upload, tiến độ
  • Tối ưu: partial reload, lazy/deferred props, prefetch, chỉ gửi dữ liệu cần thiết
  • Quản lý state toàn cục với Pinia; bật SSR khi cần SEO

Vue 3 Composition API

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
const props = defineProps<{ tasks: Task[] }>();
const filter = ref<'all' | 'open' | 'done'>('all');

const visible = computed(() =>
  filter.value === 'all' ? props.tasks : props.tasks.filter((t) => (filter.value === 'done') === (t.status === 'done'))
);

watch(filter, (f) => localStorage.setItem('task-filter', f));
</script>

<template>
  <select v-model="filter">…</select>
  <TaskRow v-for="t in visible" :key="t.id" :task="t" />
</template>
  • Reactivity dựa trên Proxy: ref cho giá trị (truy cập .value trong script), reactive cho object; destructure reactive làm mất reactivity (dùng toRefs).
  • computed cho dữ liệu dẫn xuất (được cache) — không dùng watch để sao chép state.
  • Composable (useDebounce, usePermissions) để tái sử dụng logic.
  • Luôn :key ổn định trong v-for (id, không phải index).

Mô hình Inertia

// Controller — không cần API riêng cho UI
public function index(Project $project): Response
{
    Gate::authorize('view', $project);
    return Inertia::render('Projects/Board', [
        'project' => ProjectResource::make($project),
        'tasks' => TaskResource::collection($project->tasks()->with('assignee:id,name')->get()),
        'stats' => Inertia::defer(fn () => $this->stats->for($project)),   // tải sau khi trang đã hiện
        'can' => ['create_task' => request()->user()->can('create', [Task::class, $project])],
    ]);
}

// Dữ liệu chia sẻ cho mọi trang (user, flash, quyền) — HandleInertiaRequests::share()
  • Lần đầu: server trả HTML chứa props; các lần sau: Inertia gửi XHR, server trả JSON props, client đổi trang không reload.
  • Props nằm trong HTML/JSON công khai — chỉ gửi field cần thiết qua Resource, không bao giờ gửi nguyên model.
  • router.reload({ only: ['tasks'] }) (partial reload) chỉ lấy lại một phần props; Link prefetch tải trước khi hover.
  • Inertia hỗ trợ cả React và Svelte — cùng mô hình; chọn theo team (React phổ biến hơn trên thị trường việc làm quốc tế, Vue phổ biến trong cộng đồng Laravel).

Form và validate

<script setup lang="ts">
import { useForm } from '@inertiajs/vue3';
const form = useForm({ title: '', assignee_id: null as number | null, attachment: null as File | null });
const submit = () => form.post(route('tasks.store', props.project.id), {
  preserveScroll: true,
  onSuccess: () => form.reset(),
});
</script>

<template>
  <form @submit.prevent="submit">
    <input v-model="form.title" :aria-invalid="!!form.errors.title" />
    <p v-if="form.errors.title" role="alert">{{ form.errors.title }}</p>
    <input type="file" @input="form.attachment = ($event.target as HTMLInputElement).files?.[0] ?? null" />
    <progress v-if="form.progress" :value="form.progress.percentage" max="100" />
    <button :disabled="form.processing">Tạo task</button>
  </form>
</template>

Lỗi validate của Form Request tự động xuất hiện trong form.errors — validate chỉ viết một lần ở Laravel. Optimistic UI cho thao tác nhanh (kéo thả task): cập nhật state cục bộ trước, gửi request, khôi phục khi lỗi.

State, SSR và khi nào cần SPA + API riêng

  • Pinia cho state client toàn cục thật sự (bộ lọc dùng chung nhiều trang, trạng thái editor) — dữ liệu server đã có trong props thì không copy vào store.
  • SSR của Inertia (Node process render trang lần đầu) khi cần SEO/tốc độ hiển thị đầu tiên cho trang công khai; trang dashboard sau đăng nhập thường không cần.
  • Cần SPA + REST/GraphQL API riêng khi: có mobile app/đối tác dùng chung API, frontend team độc lập, hoặc dùng Nuxt/Next.js. Khi đó TanStack Query (Vue Query) quản lý dữ liệu server.

🏋️ Bài tập thực hành

Giao diện capstone bằng Vue + Inertia

Dựng frontend capstone bằng starter kit Vue + Inertia + TypeScript: (1) danh sách project, board Kanban kéo thả (vuedraggable) với optimistic update; (2) form tạo/sửa task có upload và hiển thị lỗi 422; (3) deferred props cho thống kê project; (4) partial reload khi nhận sự kiện Reverb (Module 9); (5) composable usePermissions đọc can từ props; (6) bộ lọc lưu trên URL query string. Kiểm tra trong DevTools: props không chứa field nhạy cảm.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Dùng đúng ref/reactive/computed/watch và composable
  • Giải thích được luồng request lần đầu và các lần sau của Inertia
  • Form hiển thị lỗi validate từ Laravel, props không chứa dữ liệu nhạy cảm
  • Biết khi nào cần SPA + API riêng thay vì Inertia