Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue 3 Routing (Vue Router)

Vue 3 Routing (Vue Router)

In this chapter we introduce Vue Router.

Vue Router allows us to access different content through different URLs.

With Vue you can build a multi-view single page web application (SPA).

Vue.js routing requires loading the vue-router library

Chinese documentation address:vue-router documentation.

Vue Router is responsible for mapping URL paths to components in the application. When the user navigates in the app, the URL updates but the page does not reload, providing a smooth user experience.

The diagram above shows atwo-level nested routing structure:

Core Components

Component Description Options API Access Composition API Access
router Example 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 the current URL, params, query, and other information. this.$route useRoute()
A component used for navigation in the app, rendered as a tag, but it can prevent the default page refresh. - -
The component matched by the route will be rendered at this location. - -

Installation

npm install



npm install vue-router

npm (domestic mirror)

It is recommended to use the Taobao mirror:



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.js

import { 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.js

import { 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 }

Visiting /user/10, $route.params.id === '10'.

6. Lazy Loading



const About = () => import('../views/About.vue')

7. Navigation Guards (Auth)

router.beforeEach((to, from, next) => {

  next()

})

8. Redirect



{ path: '/old', redirect: '/' }

9. 404



{ path: '/:pathMatch(.*)*', component: NotFound }


Simple Example

Vue.js + vue-router makes it easy to implement a single-page application.

is a component used to set up a navigation link that switches different HTML content. to The attribute is the target address, that is, the content to display.

In the example below we add vue-router, then configure the components and route mappings, and tell vue-router where to render them. The code is as follows:

HTML Code

<div id="app">
<h1>

Hello App!

h1

<

p

<

router-link

to

=

"

/

"

Go to Home

router-link

<

router-link

to

=

"

/about

"

Go to About

router-link

p

<

router-view

router-view

div

Note that we do not use 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 later how to benefit from these features.

router-view

router-view will display the component corresponding to the url. You can place it anywhere to fit your layout.

JavaScript Code

//

  1. Define route components.

//

You can also import from other files

const

Home

=

{

template

:

'

Home

'

}

const

About

=

{

template

:

'

About

'

}

//

  1. Define some routes

//

Each route needs to be mapped to a component.

//

We will discuss nested routes later.

const

routes

=

[

{

path

:

'

/

'

,

component

:

Home

}

,

{

path

:

'

/about

'

,

component

:

About

}

,

]

//

  1. Create the router instance and pass routes Configure

//

You can enter more configuration here, but we

//

keep it simple for now

const

router

=

VueRouter

.

createRouter

(

{

//

  1. provides the history mode implementation internally. For simplicity, we use hash mode here.

history

:

VueRouter

.

createWebHashHistory

(

)

,

routes

,

//

routes: routes 's abbreviation

}

)

//

  1. Create and mount the root instance

const

app

=

Vue

.

createApp

(

{

}

)

//

Make sure use the route instance makes

//

the entire application support routing.

app

.

use

(

router

)

app

.

mount

(

'

#app

'

)

//

Now, the application is up and running!

Try it »

Clicked navigation links will get the style class "router-link-exact-active router-link-active".

Application Example

The following example covers routing'sdefine, creation, mounting, navigationandRenderingfive core steps.

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 match (placed 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

When you run this app:


Related Attributes

Next we can learn more about 's attributes.

to

represents the link to the target route. When clicked, it immediately passes the value of to to router.push(), so this value can be a string or an object describing the target location.



Home



Home





Home





Home





Home





User





Register

replace

If the replace attribute is set, clicking it calls router.replace() instead of router.push(), and no history record is left after navigation.



append

After setting the append attribute, its path is added before the current (relative) path. For example, if we navigate from /a to a relative path b, without append the path is /b, and with it the path is /a/b



tag

Sometimes you want to render as a certain tag, such as

  • . So we use tag 's prop to specify which tag, and it still listens for clicks to trigger navigation.

    foo
    
    
    
    
  • foo
  • active-class

    Sets the CSS class name used when the link is active. It can be replaced with the following code.

    
    
    

    Router Link 1 Router Link 2

    Note here that class uses active-class="_active".

    exact-active-class

    Configures the class to activate when the link is exactly matched. It can be replaced with the following code.

    Router Link 1 Router Link 2

    event

    Declares the events that can be used to trigger navigation. Can be a string or an array of strings.

    Router Link 1
    
    

    The code above sets event to mouseover, so when the mouse moves over Router Link 1, the navigated HTML content changes.


    Vue Router (v4, Vue 3) Core API Manual

    I.createRouter Configuration Item

    Configuration Item Purpose Example
    history Specify URL mode createWebHistory()
    routes Route table definition array [{ path: '/', component: Home }]
    scrollBehavior Control page scroll position { top: 0 }
    strict Whether to strictly distinguish trailing slashes true
    linkActiveClass Class when link is active 'active'
    linkExactActiveClass Class when link is exactly active 'exact-active'
    parseQuery Custom URL Query parsing (q) => ({...})
    stringifyQuery Custom URL Query serialization (obj) => 'a=1'

    II. History Factory

    API Purpose Example
    createWebHistory() Use HTML5 History mode (recommended) createWebHistory()
    createWebHashHistory() Use Hash mode (URL with #) createWebHashHistory()
    createMemoryHistory() Suitable for SSR (server-side rendering) createMemoryHistory()

    III.RouteRecord (route table item)

    Field Purpose Example
    path Route path definition /user/:id
    name Route naming name: 'User'
    component Corresponding main component UserView
    components Used for named views (multiple ) { default: A, left: B }
    redirect Redirect target redirect: '/login'
    children Define nested child routes [ { path: 'profile' } ]
    props data to the child component via params Automatically convert to component props props: true
    meta Custom meta information field { auth: true }
    alias Add an alias to the current route (multiple entries) alias: '/b'
    beforeEnter Route-exclusive 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 route records router.addRoute({ name:'Post', ... })
    router.removeRoute(name) Remove route records by name router.removeRoute('user')
    router.getRoutes() Get all route records router.getRoutes()
    router.hasRoute(name) Check whether a route with the specified name exists router.hasRoute('user')

    V. Navigation Guards

    Guard Scope Hook Signature
    router.beforeEach Global before (to, from, next) => {}
    router.beforeResolve Global resolve phase (after in-component guards and async component resolution) (to, from, next) => {}
    router.afterEach Global after (cannot block navigation) (to, from, failure) => {}
    beforeEnter Route-exclusive 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 changes) beforeRouteUpdate(to, from, next) {}
    beforeRouteLeave In-component (when leaving the component) beforeRouteLeave(to, from, next) {}

    VI. property

    property Purpose Example
    to Target route address to="/a" or :to="{ name: 'user', params: { id: 1 } }"
    replace Used during navigation router.replace()
    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. property

    property Purpose Example
    name Used for multi-view (named views) rendering
    route (Advanced) Force-specify the route object to render

    VIII.Route (current route object)

    This object is obtained through useRoute() or this.$route .

    Field Type Meaning Example
    params object Dynamic path parameter route.params.id
    query object URL query parameter route.query.q
    hash string Hash value in URL (with #) route.hash
    fullPath string Complete resolved path (including query and hash) /user/1?x=1
    name string The name of the current route 'User'
    path string Current path (excluding query and hash) /user/1
    meta object In the route configuration meta Information route.meta.auth
    matched RouteRecord[] All records matched by the route (used 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 Notes
    Named route navigation router.push({ name:'User', params:{ id:10 } }) Recommended approach, 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 and can be awaited to complete
    URL object navigation router.push({ path: '/foo', hash: '#bar' }) Full control over URL details