Table of contents
- Install and configure Vue Router
- Install Vue Router
- Configure Vue Router
- Basic concepts of Vue Router
- Introduction to the configuration items of Vue Router
- Introduction to configuration items in routes
- Routing jump
- Use the `router-link` component
- Use the `` function
- Routing parameters
- Dynamic routing
- Nested routing
- Named routes
- Router Guard
- Global Router Guard
- Route exclusive guard
- Lazy route loading
- Use import() to implement lazy loading
- Use dynamic import() method to achieve lazy loading
- Notes on using Vue Router
Vue Router is an official router manager that is deeply integrated with the core, through which it can easily provide routing management and navigation capabilities for single page applications (SPAs). Today we will talk about the use of Vue Router in Vue 3.
Install and configure Vue Router
Install Vue Router
To install Vue Router, you only need to open the terminal in the vue project and enter the following command to install:
npm installation
npm install vue-router@4
Yarn installation
yarn add vue-router@4
Configure Vue Router
In order to facilitate the maintenance and management of our subsequent code, we generally put the routing-related code into a folder. Therefore, the steps to configure Vue Router are as follows:
- Create a new router folder in the src folder and create a new file under the folder
- Introduce createRouter and createWebHashHistory methods in vue-router to introduce page files
import { createRouter,createWebHashHistory } from "vue-router";
import Home from '../views/'
import About from '../views/'
import List from '../views/'
import Detail from '../views/'
- Define a routes array in it, define routing rules in it
const routes = [
{
path:'/home',
name:Home,
component:Home
},
{
path:'/about',
component:About
},
{
path:'/list',
component:List
},
{
path:'/detail',
component:Detail
},
{
path:'/',
redirect:'/home'
}
]
- Create a routing instance using createRouter and configure the routing pattern and the routing rules defined above
const router = createRouter({
history:createWebHashHistory(),
routes
})
- At the end, use export default to export the route instance created above
export default router
- Registered route: Import the route file created above in it and use the registered route
import router from './router'
const app = createApp(App)
(router)//Register routing('#app')
- Using routing components in components
Use in<router-view>
Components to render the components to be displayed, and use them in the Tabbar component<router-link>
Component Generation Link
Code in component
<template>
<Title></Title>
<router-view></router-view>
<Tabbar></Tabbar>
</template>
<script setup>
import Tabbar from './components/';
import Title from './components/';
</script>
<style scoped>
</style>
Code in Tabbar component
<template>
<div>
<router-link to="/">Home</router-link>
<router-link to="/list">List</router-link>
<router-link to="/about">About</router-link>
</div>
</template>
<script setup>
</script>
<style scoped>
div {
position: fixed;
bottom: 0;
width: 100%;
height: 50px;
line-height: 50px;
text-align: center;
display: flex;
justify-content: space-around;
}
</style>
At this point, we have completed the configuration and construction of the route, run the program, refresh the browser, and see that the page can jump normally, realizing the routing function.
Although we have implemented a complete routing scenario above, we still need to have an in-depth understanding of the basic knowledge of Vue Router to facilitate us to better understand and use Vue Router. Below is an introduction to some basic concepts in Vue Router.
Basic concepts of Vue Router
-
Router: Vue Router provides a router for managing routing in applications. Vue Router Instantiates a Vue Router object, registers routing rules, and connects other components centered on it.
-
Routing: A route is a URL address distributed to different components. In Vue Router, routing is usually defined by path rules and corresponding components. When the browser's URL matches the routed path, the corresponding component will be loaded into the page. The route information can be obtained from the route object.
-
Routing rules: Routing rules are composed of properties such as path, component, name, meta, props, etc. Where, path represents the path of the URL, component represents the component to be rendered, name represents the route name, meta represents the route metadata, and props represents the route props data. Routing rules can be registered in Vue Router.
-
Navigation Guard: Navigation Guard is a hook function executed during route jumping, which is used to control the access permissions of the route, handle the logic before and after route jumping, etc. In Vue Router, for option APIs, commonly used navigation guards include beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave, etc.; for those who use combination API and setup functions to write components, you can add update and leave guards through onBeforeRouteUpdate and onBeforeRouteLeave respectively.
Introduction to the configuration items of Vue Router
When we use createRouter in Vue Router to create router object, it provides us with many configuration items. The sample code with complete configuration items is as follows:
const router = createRouter({
history: createWebHashHistory(),
routes: [],
scrollBehavior: () => ({ top: 0, left: 0 }),
linkActiveClass: 'active',
linkExactActiveClass: 'exact-active',
parseQuery: null,
stringifyQuery: null,
fallback: true
})
The meaning of each configuration item in the above code is as follows:
-
history
: The history mode for specifying the route, currently supportedcreateWebHistory()
andcreateWebHashHistory()
model. -
routes
: An array that defines routing rules. Each routing rule is an object, includingpath
、name
、component
andmeta
etc. -
scrollBehavior
: Configuration function that specifies the scrolling behavior during route switching. This function returns a containingx
andy
An object of the attribute indicates the position where the page scrolls after it jumps. -
linkActiveClass
: The class name of the link that specifies the activation status, the default is'router-link-active'
。 -
linkExactActiveClass
: The class name of the link that specifies the exact matching activation status, default to'router-link-exact-active'
。 -
parseQuery
andstringifyQuery
: Query parameter parsing and serialization functions used to configure routing. Normally, we don't need to configure these two functions as Vue Router already provides the default implementation. -
fallback
: A fallback mechanism used to configure whether to enable HTML5 History mode. The default value istrue
, means that when the route does not match, it will automatically fall back to the previous route in the history.
In the above configuration items, we generally only need to configure the two options of history and routes, and you can understand the other options.
Introduction to configuration items in routes
In Vue Router, routing rules are configured throughroutes
attributes are implemented.routes
Commonly used configurations in properties are as follows:
-
name
: The name of the routing rule. Can be used for programmatic navigation and routing jumps within components. -
path
: The routed path, which can contain dynamic parameters and regular expressions. For example,/user/:id
Represents the user page,:id
is a dynamic parameter. -
redirect
: Redirection rules for routes. For example,{ path: '/', redirect: '/home' }
Indicates the redirection of the route root path. -
component
: Routing the corresponding components. It can be a normal component class or an asynchronously loaded component. -
children
: The subroutine of the current route. It can be an array of routing rules or a function that dynamically generates routing rules. -
meta
: Meta-information of the route, used to describe some additional information about the route. For example, whether the route requires login, permission authentication, etc. -
components
: Multiple named view components corresponding to routes.
Routing jump
With Vue Router, we canrouter-link
Component to methods and usageFunctions are programmatically navigated to routes.
userouter-link
Components
userouter-link
The component implements routing jump, we only need to use the menu buttonrouter-link
Component wrapping and using the to method above can be redirected. The sample code is as follows:
<div>
<router-link to="/">Home</router-link>
<router-link to="/list">List</router-link>
<router-link to="/about">About</router-link>
</div>
use
function
useFunctions implement routing jump programmatically. We only need to bind the click event on the normal button and call it in the event.
()
The method can achieve jump, the sample code is as follows:
<template>
<div>
<router-link to="/">Home</router-link>
<router-link to="/list">List</router-link>
<router-link to="/about">About</router-link>
<button @click="gotoAbout">about</button>
</div>
</template>
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const gotoAbout = () => {
('/about')
}
</script>
useThe method adds a new record to the history stack, so when the user clicks the browser back button, it returns to the previous URL.
In fact, when we click<router-link>
When Vue Router calls this method internally, so click<router-link :to="...">
Equivalent to calling(...)
()
The parameters in the method can be a string path, or an object describing the address.
// String path('/users/eduardo')// Object with path({ path: '/users/eduardo' })// Named routes and add parameters to make the route create url({ name: 'user', params: { username: 'eduardo' } })// With query parameters, the result is /register?plan=private
({ path: '/register', query: { plan: 'private' } })// With hash, the result is /about#team
({ path: '/about', hash: '#team' })
Routing parameters
In Vue Router, you can route parameters and obtain parameters in the following ways
- Passing parameters through routing paths: Use dynamic route matching in routing configuration, for example:
const routes= [
{
path: '/detail/:id',
name: 'Detail',
component: Detail
}
]
Use colons to represent parameters in the routing path, and the parameter values will be put intoin object. We can call
Get the parameter, if the access address is /detail/123, we can get the value "123".
- Pass parameters through query parameters: use query parameters when routing jump, for example:
// Jump in component({
path: '/detail',
query: { id: 123 }
})// Jump in the template<router-link to="/detail?id=123">Detail</router-link>
When using query parameters in routes, the parameter value will be put intoin object. We can get the parameters by getting them. For example, if the access address is /detail?id=123, we can get the value "123".
- Pass parameters through the props option in the routing configuration. For example:
const routes= [
{
path: '/detail/:id',
name: 'Detail',
component: Detail,
props: { id: 123 }
}
]
You can directly use props to receive parameters in the component
- Pass parameters through meta options in routing configuration. For example:
const routes= [
{
path: '/detail/:id',
name: 'Detail',
component: Detail,
meta: { id: 123 }
}
]
In the component, you can obtain parameters.
Dynamic routing
Dynamic routing refers to a route that uses part of a route as a parameter. For example, if we want to create a separate page for each user, we can use dynamic routing to create a path as/users/:userId
routes, where:userId
is a parameter.
Dynamic routing uses colons when defining routes (:
) to represent parameters. Defining dynamic routing requires usepath
Method definition. For example, to define a dynamic route, we can write this:
{
path: '/users/:userId',
name: 'user',
component: User
}
In the above code, the path:userId
Represents a parameter that can be routed from theparams
Get in the attribute. This can be read in the componentuserId
:
()
When using dynamic routing, Vue Router also supports the use of optional parameters and regular expressions to define routes. For example, a dynamic route with optional parameters can be defined like this:
{
path: '/users/:userId/:postId?',
name: 'post',
component: Post
}
In the above code, the pathpostId
The parameter is optional, and we add a question mark after it to represent the optional parameter. Now, if the path is/users/123
,SopostId
Will beundefined
; if the path is/users/123/456
,SopostId
Will be456
。
Nested routing
Nested routing allows us to nest multiple child routes under a parent route, thus forming a more complex page structure.
To define nested routes, we can route them in the parent routeroutes
Define an array of subroutine objects in an array, each subroutine object contains onepath
And onecomponent
Property, indicating the access path and corresponding components of the current subroutine. At the same time, we can also define the subroutine of the subroutine in the subroutine object to form a nested routing structure.
We use configuration itemschildren
Represents the nested relationship of the route, as shown in the following example code:
const routes = [
{
path: '/',
component: Home,
children: [
{
path: 'about',
component: About
},
{
path: 'contact',
component: Contact
}
]
}
]
In the above code, we define a name calledHome
The component of the parent route is used as the component of the parent route and inchildren
Two subroutines are defined in the array:About
andContact
. In this way, when the user accesses/about
or/contact
When Vue Router renders the corresponding child components and nests them inHome
Inside the component.
Named routes
Named routes can set a name for the route to be referenced and redirected in the code. Using named routing can make the code clearer and easier to understand, especially when you need to jump to a route with dynamic parameters.
To define a named route, we can use it in the route objectname
Properties to specify the name of the route, for example:
const routes = [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: About
},
{
path: '/user/:id',
name: 'user',
component: User
}
]
In the above code, we specify names for the three routes:home
、about
anduser
. Then, in the code, we can generate the corresponding route link or route jump through these names, for example:
<router-link :to="{name: 'home'}">Home</router-link>
<router-link :to="{name: 'about'}">About</router-link>
<router-link :to="{name: 'user', params: {id: '123'}}">User 123</router-link>
({name: 'home'})
({name: 'user', params: {id: '456'}})
In the above code, we used<router-link>
Components and()
Method to jump to a route with named route. Among them, useparams
Properties can dynamically specify parameters in the route.
Named routes are very convenient to use when dynamically passing parameters.
Router Guard
A route guard is a function called at various stages of a route and can be used to intercept access to a route or perform some operations on a route. We can use the route guard to control the route's jump and access permissions.
In the route guard, we usually use three parameters:to
、from
andnext
。
-
to
: Indicates the target routing object to be redirected, including information such as route path, parameters, query strings, etc. -
from
: Indicates the current routing object, that is, the route object that is leaving. -
next
: is a function used for routing control and jumping. When callednext
When the function is used, the route will continue to be executed downward. We can passnext
Functions to control the behavior of routing, such as rendering components, jumping routes, canceling operations, etc.
Several usesnext
The situation of the function
-
next()
: Indicates that the next route guard will continue to be executed. -
next(false)
: Indicates that the current route jump is cancelled. -
next('/path')
: Indicates jumping to the specified route path. -
next(error)
: Indicates that an error occurred during the routing jump, such as insufficient permissions, etc.
It should be noted that when using route guards, we need to explicitly call themnext
Functions to control the route's jump and function, otherwise the route will not continue to be executed downward. Among the different guards,next
The behavior and functions of functions will also be different and need to be called according to the specific scenario.
Router guards in Vue Router are divided into global router guards and route exclusive guards:
Global Router Guard
Global routing guards are guards that take effect throughout the application and can be used to intercept all routing operations. In Vue Router@4, there are three global guards:beforeEach
、beforeResolve
andafterEach
。
-
beforeEach
: Execute before routing jump, which can be used for global access control or redirect jump and other operations. -
beforeResolve
: Execute before the route jump is completed, which can be used to wait for the asynchronous routing component to complete loading or perform some operations before the route jump. -
afterEach
: Execute after the routing jump is completed, it can be used to perform some operations on the page, such as monitoring page burying points or modifying page titles.
A route guard sample code that verifies whether the user is logged in is as follows
((to, from, next) => {
if ( !== 'Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})
In the above code, if the user is not logged in, the page will jump to the Login page. If you are already logged in, then next() will be performed.
Route exclusive guard
The route exclusive guard is only valid for the current route and can be used to restrict or enhance access to a route. In Vue Router@4, there are two router exclusive guards:beforeEnter
andleaveGuard
。
-
beforeEnter
: Execute before entering the current route, which can be used to enhance access rights to the current route or perform related operations. -
leaveGuard
: Execute before leaving the current route, which can be used to prompt the user or perform related operations.
When using route guards, we cancreateRouter
Register in the function, for example:
const routes=[
{
path: '/',
component: Home
},
{
path: '/about',
component: About,
beforeEnter: (to, from, next) => {// Perform routing access control or related operations}
}
]
Lazy route loading
Lazy loading of routing is a way to load routing components asynchronously on demand. The code corresponding to the routing component will be dynamically loaded only when the corresponding component needs to be used. Using lazy routing can optimize application performance
Using laziness loading in Vue Router, we can useimport()
and dynamicsimport()
Two ways to achieve
Use import() to implement lazy loading
const Home = () => import('./views/')
const About = () => import('./views/')
const routes = [
{
path: '/',
component: Home
},
{
path: '/about',
component: About
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
Use dynamic import() method to achieve lazy loading
const routes = [
{
path: '/',
component: () => import('./views/')
},
{
path: '/about',
component: () => import('./views/')
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
Notes on using Vue Router
-
Dynamic parameters cannot have slashes: When using dynamic parameters, please note that the URL cannot be the same as the dynamic parameters.
-
Navigation process: The route is similar to the stack, and each route jump will be recorded by the history records in the historical records. If you jump to the same route, the last few times in the history will be ignored. By default, newly jumped routes will not trigger the route update process, you need to use it explicitly.
or
Method to update to the current route.
-
Navigation canceled: If you are in
beforeRouteLeave
orbeforeRouteUpdate
An asynchronous operation is performed in the guard, you must ensure that the asynchronous operation has been completed and callednext(true)
to ensure navigation can be performed.
OK, that’s all about the relevant content on using Vue Router in vue3. If you have any questions, leave a message in the comment area. If you like it, like it and follow it and collect it! !