tezvyn:

Declarative Route Configuration in Vue

AI-drafted, machine-checkedSource: router.vuejs.orgintermediate

Declarative routing maps URL paths to components like a switchboard. You define a list of routes, and the framework renders the correct view when the URL changes. This is standard for SPAs.

WHY IT EXISTS Single-Page Applications (SPAs) offer a fluid user experience by updating content without full page reloads. This requires a system to synchronize the browser's URL with the visible content on the client-side, which is precisely the problem that client-side routers solve.

THE MENTAL MODEL Think of declarative route configuration as a telephone switchboard's directory. You provide a simple, readable list that maps an incoming "call" (a URL path like /users/42) to a specific "extension" (a UI component). You don't manually wire the connection each time; you just define the map once, and the router handles the switching automatically.

HOW IT WORKS In Vue, you use the createRouter function to build a router instance. The core of this is the routes option, which takes an array of route objects. Each object must contain at least a path property (a string for the URL) and a component property (the Vue component to render). You then use two special components in your templates: <RouterLink to="/path"> creates navigation links that update the URL without a page reload, and <RouterView /> acts as a placeholder where the matched component will be rendered.

WHEN TO USE IT This is the standard pattern for any Single-Page Application built with a modern framework like Vue, React, or Angular. Use it whenever you need to associate different browser URLs with different views or component layouts within your application, creating the illusion of multiple pages while maintaining the performance benefits of an SPA.

WHEN NOT TO USE IT For very simple applications with only one view, a router is overkill. It's also not the primary mechanism for traditional multi-page applications (MPAs) where each URL corresponds to a separate HTML file served by a backend server. In those cases, server-side routing handles navigation.

ONE CANONICAL EXAMPLE To set up routes, you create an array of objects:

const routes = [ { path: '/', component: HomeView }, { path: '/about', component: AboutView } ]

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

This configuration tells Vue that when the user is at the root URL (/), it should render the HomeView component inside the <RouterView>. When they navigate to /about, it will render the AboutView component instead.

Read the original → router.vuejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.