Master Vue Router Efficient SPA Vue.js Navigation [Practical Example]

Master Vue Router Điều Hướng SPA Vue.js Hiệu Quả [Ví Dụ Thực Tế]

Tired of slow website loads and white flashes every time a link is clicked? That's when Vue Router SPA Vue.js steps in to save the day. It is the "heart" of every single page application (SPA) built using the Vue ecosystem, helping to create a smooth, seamless user experience like using a real desktop application. This article does not contain boring theories. With many years of practical experience, I will walk with you from the first installation step, through practical examples to the most advanced techniques to completely master the flow of your project.

Why is Vue Router "required" for every Vue.js SPA?

Using Vue Router is the most optimal solution to manage routing flows in SPA applications, helping to change website content immediately without sending a request to reload all resources from the server.

Seamless user experience - Say no to "blank pages" when reloading

In the old days of traditional web development (MPA), every time the user switched pages, the browser had to reload all the HTML, CSS, and JavaScript. This causes an extremely annoying "white flash" on the screen. Now, when making SPA (Single Page Application) with Vue.js, everything changes with just JavaScript. Updating the DOM happens instantly on the client side. If you are a newbie who is not familiar with this framework and how it manipulates the DOM, I recommend taking a look at the article Learn Vue.js 3 from scratch for beginners before delving into the routing system.

What is Vue Router? Simply put, it means the "coordinator" of the application

Imagine your web application is a large office building, then Vue Router is the receptionist holding a map in the lobby. When a user types a URL into the browser, this "receptionist" will look at the routing configuration and specify exactly which components should be displayed on the screen. Thanks to this intelligent mechanism, Vue Router for SPA applications becomes the indispensable industry standard for smooth navigation.

Các khái niệm cốt lõi cần nắm: router-view, router-link, và routes

To start learning how to use Vue Router, you don't need to remember too many complicated things. Let's deepen the following 3 core concepts:

  • routes (Route object): Là một mảng chứa các quy tắc bản đồ. Nó khai báo rõ ràng URL nào sẽ tương ứng với Component nào.
  • router-link: Đây là thẻ component đặc biệt dùng để thay thế cho thẻ <a> truyền thống trong HTML. Khi click vào, nó thay đổi URL mà không làm reload trang.
  • router-view: Điểm neo (placeholder). Đây là khung cửa sổ nơi Vue sẽ render nội dung của Component tương ứng với URL hiện tại.

Get started: Install and configure Vue Router in 5 minutes

Setting up Vue Router is extremely quick through modern package managers, then you just need to instantiate the router instance and attach it to the main Vue application.

Install Vue Router 4 into Vue 3 project (using npm/Vite)

Hầu hết anh em lập trình viên tính đến năm 2026 đều đã chuyển sang xài Vite thay vì Vue CLI cũ kỹ vì tốc độ build cực nhanh của nó. Mở terminal trong thư mục dự án của bạn lên và gõ lệnh npm install vue-router@4. Đảm bảo bạn đang cài đặt phiên bản số 4 nhé, vì đây là bản được viết lại hoàn toàn để tối ưu cho Vue 3 Composition API. Bất kỳ tài liệu Vue Router 4 hướng dẫn chuẩn mực nào cũng sẽ bắt đầu bằng bước cài đặt gói npm này.

Configure the first router file: Mapping URL to Component

Tạo một file mới tại đường dẫn src/router/index.js. Tại đây, chúng ta sẽ định nghĩa mảng routes và khởi tạo router. Việc cấu hình Vue Router để map URL với Component khá trực quan và dễ đọc. Tiện thể, nếu bạn từng làm việc với các hệ sinh thái JavaScript khác, bạn sẽ thấy nó có triết lý khai báo khá tương đồng với cách React Router điều hướng trang SPA, đều dựa trên tư tưởng component-based.

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  { path: '/', component: HomeView },
  { path: '/about', component: () => import('../views/AboutView.vue') }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

export default router

Lựa chọn chế độ lịch sử: Khi nào dùng createWebHistory và khi nào dùng createWebHashHistory?

Vue Router history modes determine how your URLs look in the address bar. Choosing the right mode greatly affects SEO and deployment.

History mode Initialization function URL characteristics When should it be used?
HTML5 History Mode createWebHistory() Sạch đẹp: domain.com/about Chuẩn mực cho web thực tế, tốt cho SEO. Yêu cầu cấu hình server (Nginx/Apache) trỏ mọi request về index.html.
Hash Mode createWebHashHistory() Có dấu #: domain.com/#/about Easy setup, no server configuration required. Suitable for internal tools, apps that do not need SEO.
Memory Mode createMemoryHistory() Do not change the URL Used in Node.js (SSR) environment or when writing Unit Test.

Important navigation techniques you'll use every day

Managing flexible navigation with code, passing data via parameters (params) and query strings (queries) are vital skills when working with Vue Router.

Điều hướng bằng chương trình: router.push() cho các hành động như login, logout

Không phải lúc nào người dùng cũng chủ động click vào router-link. Giả sử khi họ submit form đăng nhập thành công, bạn phải dùng code để tự động chuyển họ vào trang chủ. Đó là lúc điều hướng bằng chương trình trong Vue Router tỏa sáng.

Mình thường xuyên dùng router.push('/dashboard') để chuyển trang và thêm một bản ghi vào lịch sử trình duyệt. Nếu bạn không muốn user bấm nút Back để quay lại trang login vừa rồi, hãy xài router.replace(). Còn khi muốn làm nút quay lại trang trước đó, router.go(-1) hoạt động y hệt nút Back trên trình duyệt.

Truyền tham số động cho route: Ví dụ với trang chi tiết sản phẩm /san-pham/:id

Làm web thương mại điện tử hoặc blog thì 100% bạn phải dùng Dynamic Routes. Để truyền tham số cho route Vue Router, bạn định nghĩa path có chứa dấu hai chấm: path: '/san-pham/:id'.

Khi user truy cập vào /san-pham/123, Route Parameters id sẽ mang giá trị là 123. Bên trong component chi tiết sản phẩm, bạn có thể lấy giá trị này ra dễ dàng để gọi API lấy đúng thông tin món hàng đó hiển thị cho người dùng.

Sử dụng Query Params để lọc dữ liệu: Ví dụ với trang tìm kiếm /tim-kiem?q=vuejs

Khác với params (nằm trong path), Query Parameters nằm sau dấu ? trên URL. Việc quản lý query params Vue Router cực kỳ hữu ích cho các chức năng lọc, tìm kiếm hoặc phân trang.

Ví dụ, bạn có thể đẩy user đến trang kết quả bằng lệnh: router.push({ path: '/tim-kiem', query: { q: 'vuejs', page: 2 } }). URL sinh ra (/tim-kiem?q=vuejs&page=2) sẽ cực kỳ thân thiện, giúp người dùng dễ dàng copy link chia sẻ cho người khác mà vẫn giữ nguyên được trạng thái bộ lọc.

Pass Props directly into the component from the route for cleaner code

Thay vì cứ phải gọi $route.params.id lặp đi lặp lại trong phần template hay script gây vướng víu và ràng buộc chặt chẽ, thư viện này cung cấp một lối thoát tuyệt vời. Bằng cách truyền props vào component route Vue Router (đặt props: true trong file cấu hình index.js), tham số URL sẽ được tự động đẩy vào component dưới dạng props thông thường. Kỹ thuật này giúp component của bạn hoàn toàn độc lập với router, từ đó dễ dàng tái sử dụng và viết unit test hơn rất nhiều.

Upskilling: Secure and optimize performance with Vue Router

Applying Navigation Guards to control access and Lazy Loading to reduce JavaScript file size are two important steps that help make applications secure and load faster.

Protect route with Navigation Guards: For example, login is required to access the admin page

This is the "potato" part but the most valuable to distinguish the novice from the skilled worker. Protect routes in Vue Router with Navigation Guards just like you would set up security checkpoints. You have Global Guards (run every time when turning pages), Per-route Guards (run for a specific route) and In-component Guards.

Kết hợp với Meta Fields (ví dụ gán meta: { requiresAuth: true } cho route admin), mình thường xuyên viết logic kiểm tra xem user đã có token hay chưa ở hàm router.beforeEach(). Việc xác thực người dùng với Vue Router diễn ra tại đây: Nếu chưa có Authentication hoặc Authorization hợp lệ, mình sẽ đá văng họ về trang login ngay lập tức. Đừng quên gọi hàm next() đúng cách để luồng điều hướng được tiếp tục nhé.

Build complex layouts with Nested Routes

Real applications rarely have just one simple level of interface. For example, the Admin Dashboard page usually has a fixed Sidebar on the left, Header above, and only the content in the middle changes when the menu is clicked.

Định tuyến lồng nhau Vue Router (Nested Routes) sinh ra để giải quyết bài toán này. Bằng cách khai báo thuộc tính children trong mảng cấu hình route cha. Kỹ thuật Vue Router nâng cao này giúp cấu trúc code cực kỳ gọn gàng. Component cha chỉ cần chứa một thẻ router-view riêng biệt để làm nơi render động cho các component con bên trong nó.

Speed ​​up page loading with Lazy Loading Routes (Code Splitting)

If you import all the components right at the beginning of the router file using normal syntax, your Bundle Size will balloon to a huge size. Users entering the homepage will have to download the code for the admin page, profile page... causing long waiting times.

Để tối ưu hiệu suất Vue Router, bắt buộc phải dùng Lazy loading route Vue Router. Bằng cách sử dụng cú pháp dynamic import () => import('./views/About.vue') hoặc hàm defineAsyncComponent, các công cụ build như Webpack hay Vite sẽ tự động thực hiện Code Splitting. Nghĩa là user vào trang nào, trình duyệt mới tải đoạn code JavaScript của trang đó. Đây là một kỹ thuật Performance Optimization kinh điển. Nhân tiện, nếu bạn tò mò về hiệu năng tổng thể và cách xử lý bundle của các framework hiện nay, bài viết So sánh React vs Vue vs Angular 2026 có những số liệu phân tích rất thú vị.

"Bloody" experience: Common problems and solutions

In real life, handling API Composition, scrolling control, and 404 error pages requires small tricks but brings big effects to user experience (UX).

Sử dụng useRouter()useRoute() trong Composition API

Trong môi trường Vue 3 với cú pháp <script setup>, chúng ta không còn quyền truy cập vào biến this.$router hay this.$route như thời Vue 2 nữa. Thay vào đó, bạn phải import các composable functions.

Sử dụng useRouter() khi bạn muốn thực hiện hành động chuyển trang, và useRoute() để lấy thông tin chi tiết về URL hiện tại (params, query). Một lưu ý nhỏ từ kinh nghiệm của đội ngũ Phạm Hải là hãy cẩn thận khi dùng chúng bên trong các Lifecycle Hooks. Hãy đảm bảo router instance đã sẵn sàng (mounted) trước khi gọi các API phụ thuộc vào tham số URL để tránh lỗi undefined.

Manage Scroll Behavior: Automatically scroll to the top of the page when switching routes

An extremely annoying UX mistake that many newbies often make is: When the user scrolls to the bottom of page A, clicks the link to page B and page B remains in the scrolled position at the bottom.

Trong các ví dụ Vue Router thực tế chuyên nghiệp, mình luôn cấu hình hàm scrollBehavior ngay trong lúc khởi tạo router. Chỉ cần thiết lập cho hàm này return { top: 0 }, mọi trang mới khi được mở ra sẽ luôn bắt đầu hiển thị từ trên cùng. Một dòng code nhỏ nhưng cứu vớt toàn bộ trải nghiệm người dùng.

Handle 404 (Not Found) pages professionally

Người dùng gõ sai URL hoặc truy cập vào link cũ đã chết là chuyện xảy ra như cơm bữa. Bạn cần thiết lập một route đặc biệt dùng regex /:pathMatch(.*)* và đặt nó ở vị trí cuối cùng trong mảng routes để "vớt" mọi URL không hợp lệ, từ đó điều hướng họ về một trang 404 custom đẹp mắt.

However, if your project requires extremely strict SEO and needs to return a standard 404 status code from the server to the Google bot (instead of just displaying the 404 interface on the client), you should consider applying Server-Side Rendering (SSR). At this time, consulting Nuxt.js framework Vue SSR guide will be a great solution, helping to completely solve the SEO problem that pure Vue Router is difficult to do.

At Pham Hai, we realize that mastering Vue Router navigating SPA Vue.js is not just about memorizing a few API syntax, but about practicing the thinking of organizing application architecture. From basic configuration setup, setting up security barriers with Navigation Guards to squeezing every kilobyte with Lazy Loading, everything serves a single purpose: Providing the fastest, smoothest and safest experience for end users. Don't just read, open your editor, create a new Vite project and type in the techniques I just shared.

Are you having any strange problems or bugs with Navigation Guards, or have any better optimization tips for working with Vue Router? Please feel free to share in the comments section below, let's discuss and learn from each other!

Lưu ý: Những thông tin trong bài viết này chỉ mang tính chất tham khảo. Để có được lời khuyên tốt nhất, vui lòng liên hệ trực tiếp với chúng tôi để được tư vấn cụ thể dựa trên nhu cầu thực tế của bạn.

Categories: Lập Trình Web Vue.js

mrhai

Để lại bình luận