Hello App!
Go to HomeGo to About
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
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 |
YouTip