YouTip LogoYouTip

Vue3 Routing

In this chapter, we will introduce Vue Routing. Vue routing allows us to access different content through different URLs. With Vue, we can implement a single-page web application (SPA) with multiple views. Vue.js routing requires loading the (https://github.com/vuejs/router). Chinese documentation: (https://router.vuejs.org/zh/guide/). Vue Router is responsible for mapping URL paths to components within the application. When users navigate within the application, the URL updates, but the page does not reload, providing a smooth user experience. !(#) The image above illustrates a **two-level nested routing structure**: * **Top-level (`App.vue`'s ``)** is responsible for rendering **standalone layouts** (like `Login.vue`) or the **main framework layout** (`Layout.vue`). * **The main framework layout (`Layout.vue`)** contains a second `` inside, used to render **sub-components of functional pages** (like `Dashboard.vue`, `User.vue`), thereby achieving persistent display of the header, sidebar, and footer. * Unmatched paths ultimately lead to the standalone `page404.vue`. ### Core Components | Component | Description | Options API Access | Composition API Access | | --- | --- | --- | --- | | **`router` instance** | The instance of the entire routing system, used for global navigation, adding routes, etc. | `this.$router` | `useRouter()` | | **`route` object** | The currently active route state object, containing information about the current URL, parameters, query, etc. | `this.$route` | `useRoute()` | | **``** | A component used for navigation within the application. It renders as an `` tag but can prevent the default page refresh. | - | - | | **``** | The component matched by the route will be rendered in this location. | - | - | * * * ## Installation ### npm Installation npm install vue-router ### npm (China Mirror) Using the Taobao mirror is recommended: npm install -g cnpm --registry=https://registry.npmmirror.com cnpm install vue-router@4 ### Direct Download / CDN https://unpkg.com/vue-router@4 ### Basic Application ### 1. Create the Route Table // src/router/index.jsimport { createRouter, createWebHistory } from 'vue-router'import Home from '../views/Home.vue'import About from '../views/About.vue'const routes = [ { path: '/', component: Home }, { path: '/about', component: About }]export default createRouter({ history: createWebHistory(), routes }) ### 2. Mount in the Application // main.jsimport { createApp } from 'vue'import App from './App.vue'import router from './router' createApp(App).use(router).mount('#app') ### 3. Page Outlet ### 4. Navigation About ### 5. Dynamic Routes { path: '/user/:id', component: User } Accessing /user/10, `$route.params.id === '10'`. ### 6. Lazy Loading const About = () => import('../views/About.vue') ### 7. Navigation Guards (Authentication) router.beforeEach((to, from, next) => { next()}) ### 8. Redirect { path: '/old', redirect: '/' } ### 9. 404 { path: '/:pathMatch(.*)*', component: NotFound } * * * ## Simple Example Vue.js + vue-router can easily implement a single-page application. **``** is a component used to set a navigation link, switching between different HTML content. The **`to`** attribute is the target address, i.e., the content to be displayed. In the following example, we add vue-router, then configure the component and route mapping, and finally tell vue-router where to render them. The code is as follows: ## HTML Code

Hello App!

Go to HomeGo to About

### router-link Note that we are not using a regular `a` tag, but a custom component `router-link` to create links. This allows Vue Router to change the URL without reloading the page, handling URL generation and encoding. We will see how to benefit from these features later. ### router-view `router-view` will display the component corresponding to the URL. You can place it anywhere to suit your layout. ## JavaScript Code const Home = {template: '
Home
'}const About = {template: '
About
'}const routes = [{path: '/', component: Home}, {path: '/about', component: About}, ]const router = VueRouter.createRouter({history: VueRouter.createWebHashHistory(), routes, })const app = Vue.createApp({})app.use(router)app.mount('#app') [Try it Β»](#) Clicked navigation links will have the style class `router-link-exact-active router-link-active` added. ### Application Instance The following example covers the five core steps of routing: **definition**, **creation**, **mounting**, **navigation**, and **rendering**. **1. main.js (Entry File)** ## Example import{ createApp } from 'vue'; import App from './App.vue'; import router from './router';// Import the configured router instance // 1. Create the Vue application instance const app = createApp(App); // 2. Mount the router app.use(router); // 3. Mount to the DOM app.mount('#app'); **2. router/index.js (Route Configuration)** ## Example import{ createRouter, createWebHistory } from 'vue-router'; // Import route components (synchronous import used here to simplify the example) const Home ={ template:'

Home Page

Welcome to the application home!

'}; const About ={ template:'

About Us

Learn more about this project.

'}; // Define the route records array const routes =[ { path:'/', name:'Home', component: Home }, { path:'/about', name:'About', component: About }, // 404 catch-all (place last) { path:'/:pathMatch(.*)*', name:'NotFound', component:{ template:'
404 Not Found
'} } ]; // Create the Router instance const router = createRouter({ // Use HTML5 History mode (recommended) history: createWebHistory(), routes,// Route configuration }); export default router; **3. App.vue (Root Component)** ## Example

Vue Router Example


/* Simple active style */ .active-link { font-weight: bold; color: #42b983; /* Vue green */ } /* Adjust link spacing */ nav a { margin: 0 5px; text-decoration: none; } When you run this application: * Clicking the **Home** link changes the URL to `/`, and the `Home Page` component content is displayed in ``. * Clicking the **About** link changes the URL to `/about`, and the `About Us` component content is displayed in ``. * Clicking the **404 Demo** link changes the URL to `/nonexistent`, and the `404 Not Found` component content is displayed in ``. * * * ## `` Related Attributes Next, we can learn more about the attributes of ``. ### to Represents the link to the target route. When clicked, the value of `to` is immediately passed to `router.push()`, so this value can be a string or an object describing the target location. Home
HomeHomeHomeHomeUserRegister ### replace If the `replace` attribute is set, clicking will call `router.replace()` instead of `router.push()`, and no history record will be left after navigation. ### append If the `append` attribute is set, the path is added before the current (relative) path. For example, if we navigate from `/a` to a relative path `b`, without `append` configured, the path is `/b`; if configured, it is `/a/b`. ### tag Sometimes you want `` to render as a certain tag, like `
  • `. So we use the `tag` prop to specify which tag, and it will still listen for clicks and trigger navigation. foo
  • foo
  • ### active-class Sets the CSS class name used when the link is active. This can be overridden with the following code. ._active{ background-color : red; }

    Router Link 1 Router Link 2

    Note that here **class** uses `active-class="_active"`. ### exact-active-class Configures the class to be activated when the link is exactly matched. This can be overridden with the following code.

    Router Link 1 Router Link 2

    ### event Declares the event that can be used to trigger navigation. It can be a string or an array containing strings. Router Link 1 The code above sets the event to `mouseover`, meaning the HTML content of Router Link 1 will change when the mouse moves over it. * * * ## Vue Router (v4, Vue 3) Core API Manual ### I. `createRouter` Configuration Options | Option | Purpose | Example | | --- | --- | --- | | **`history`** | Specifies the URL mode | `createWebHistory()` | | **`routes`** | Array defining the route table | `[{ path: '/', component: Home }]` | | **`scrollBehavior`** | Controls page scroll position | `{ top: 0 }` | | **`strict`** | Whether to strictly distinguish trailing slashes | `true` | | **`linkActiveClass`** | Class for active links | `'active'` | | **`linkExactActiveClass`** | Class for exactly active links | `'exact-active'` | | **`parseQuery`** | Custom URL Query parsing | `(q) => ({...})` | | **`stringifyQuery`** | Custom URL Query serialization | `(obj) => 'a=1'` | ### II. History Factories | API | Purpose | Example | | --- | --- | --- | | **`createWebHistory()`** | Uses HTML5 History mode (recommended) | `createWebHistory()` | | **`createWebHashHistory()`** | Uses Hash mode (URL with `#`) | `createWebHashHistory()` | | **`createMemoryHistory()`** | Suitable for SSR (Server-Side Rendering) | `createMemoryHistory()` | ### III. `RouteRecord` (Route Table Entry) | Field | Purpose | Example | | --- | --- | --- | | **`path`** | Route path definition | `/user/:id` | | **`name`** | Route name | `name: 'User'` | | **`component`** | Corresponding main component | `UserView` | | **`components`** | For named views (multiple ``) | `{ default: A, left: B }` | | **`redirect`** | Redirect target | `redirect: '/login'` | | **`children`** | Defines nested child routes | `[ { path: 'profile' } ]` | | **`props`** | Automatically converts `params` to component `props` | `props: true` | | **`meta`** | Custom meta information fields | `{ auth: true }` | | **`alias`** | Adds an alias for the current route (multiple entry points) | `alias: '/b'` | | **`beforeEnter`** | Route-specific navigation guard | `{ beforeEnter: (to,from,next)=>{} }` | ### IV. Route Navigation (Router Instance Methods) | Router API | Purpose | Example | | --- | --- | --- | | **`router.push(to)`** | Programmatic navigation, adds a new record to the history stack | `router.push('/a')` | | **`router.replace(to)`** | Programmatic navigation, replaces the current history record | `router.replace('/a')` | | **`router.back()`** | Go back one step | `router.back()` | | **`router.forward()`** | Go forward one step | `router.forward()` | | **`router.go(n)`** | Manually offset the history stack | `router.go(-1)` | | **`router.addRoute(route)`** | Dynamically add a route record | `router.addRoute({ name:'Post', ... })` | | **`router.removeRoute(name)`** | Remove a route record by name | `router.removeRoute('user')` | | **`router.getRoutes()`** | Get all route records | `router.getRoutes()` | | **`router.hasRoute(name)`** | Check if a route with the specified name exists | `router.hasRoute('user')` | ### V. Navigation Guards | Guard | Scope | Hook Signature | | --- | --- | --- | | **`router.beforeEach`** | Global before each | `(to, from, next) => {}` | | **`router.beforeResolve`** | Global before resolve (after in-component guards and async components are resolved) | `(to, from, next) => {}` | | **`router.afterEach`** | Global after each (cannot prevent navigation) | `(to, from, failure) => {}` | | **`beforeEnter`** | Route-specific | `beforeEnter: (to, from, next) => {}` | | **`beforeRouteEnter`** | In-component (cannot access `this`) | `beforeRouteEnter(to, from, next) {}` | | **`beforeRouteUpdate`** | In-component (when the current route is reused, e.g., parameter change) | `beforeRouteUpdate(to, from, next) {}` | | **`beforeRouteLeave`** | In-component (when leaving the component) | `beforeRouteLeave(to, from, next) {}` | ### VI. `` Attributes | Attribute | Purpose | Example | | --- | --- | --- | | **`to`** | Target route address | `to="/a"` or `:to="{ name: 'user', params: { id: 1 } }"` | | **`replace`** | Use `router.replace()` during navigation | `` | | **`custom`** | Custom rendering, used with slots | `` | | **`active-class`** | Class applied when the link is active | `'active'` | | **`exact-active-class`** | Class applied when the link is exactly matched | `'exact'` | ### VII. `` Attributes | Attribute | Purpose | Example | | --- | --- | --- | | **`name`** | Used for multi-view (named view) rendering | `` | | **`route`** | (Advanced) Forces the rendering of a specific route object | `` | ### VIII. `Route` (Current Route Object) This object is obtained via `useRoute()` or `this.$route`. | Field | Type | Meaning | Example | | --- | --- | --- | --- | | **`params`** | `object` | Dynamic path parameters | `route.params.id` | | **`query`** | `object` | URL query parameters | `route.query.q` | | **`hash`** | `string` | Hash value in the URL (with `#`) | `route.hash` | | **`fullPath`** | `string` | Fully resolved path (including query and hash) | `/user/1?x=1` | | **`name`** | `string` | Name of the current route | `'User'` | | **`path`** | `string` | Current path (without query and hash) | `/user/1` | | **`meta`** | `object` | `meta` information from the route configuration | `route.meta.auth` | | **`matched`** | `RouteRecord[]` | All records matched by the route (for nested routes) | `route.matched` | ### IX. Composition API | API | Purpose | Example | | --- | --- | --- | | **`useRoute()`** | Get the current route object (`Route`) | `const route = useRoute()` | | **`useRouter()`** | Get the router instance (`Router`) | `const router = useRouter()` | ### X. Programmatic Navigation (Complete Example) | Purpose | Example | Note | | --- | --- | --- | | **Named route navigation** | `router.push({ name:'User', params:{ id:10 } })` | Recommended, does not depend on path order | | **Navigation with Query parameters** | `router.push({ path:'/search', query:{ q:'x' } })` | Path + query parameters | | **Awaitable Push/Replace** | `await router.push('/a')` | Navigation is asynchronous, can be awaited to complete | | **URL object navigation** | `router.push({ path: '/foo', hash: '#bar' })` | Full control over URL details |
    ← Number MinNumber Ceil β†’