Basic usage of VueRouter for Vue learning
Basic use of VueRouter
VueRouter is a routing management library officially supported by Vue.js, which can help us easily implement SPA single-page applications. This article will introduce the usage of VueRouter in detail, including related APIs, methods and properties.
basic usage
Install and import
First, we need to install VueRouter in the project, which can be installed using npm or yarn:
npm install vue-router
or
yarn add vue-router
After the installation is complete, we need to introduce VueRouter in the Vue project and use it:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
// 配置路由映射关系
]
})
new Vue({
router,
render: h => h(App)
}).$mount('#app')
Initialize the VueRouter instance
When creating a VueRouter instance, we need to pass in an routes
array to configure the route mapping relationship.
routes
Each item in the array is a routing configuration object, which contains the following properties:
path
: route path, which can be a string or a regular expressionname
: route namecomponent
: The component corresponding to the routeredirect
: redirect routealias
:alias routemeta
: Meta information, which can be used when switching routes. Here is a simple example:
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
]
In Vue components, we can use <router-link>
components to create links and use <router-view>
components to display corresponding components. For example:
<template>
<div>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
</div>
</template>
The attribute here to
can be a string or a routing configuration object.
Related APIs and methods, attributes
method
router.beforeEach
This method will be executed before each routing jump, and can be used for some authority control or global routing guards.
router.beforeEach((to, from, next) => {
// to:即将跳转的路由对象
// from:当前所在的路由对象
// next:必须调用该方法才能跳转到下一个路由
// 如果不调用该方法,则不会跳转
next()
})
Here is a simple example:
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token') if (to.name !== 'Login' && !isAuthenticated) next({
name: 'Login' }) else next() })
In this example, we determine whether the user has logged in, and if not logged in and not going to the login page, we will forcefully jump to the login page.
router.afterEach
This method will be executed after each route jump, and can be used to do some processing after page switching, such as scrolling the page to the top, etc.
router.afterEach((to, from) => {
// to:即将跳转的路由对象
// from:当前所在的路由对象
window.scrollTo(0, 0)
})
In this example, we scroll the page to the top after a page jump.
router.push
This method is used to jump to a new route, which can be a string or a route configuration object.
router.push('/')
In this example, we jump to the root route.
router.replace
This method is used to replace the current route, which can be a string or a route configuration object.
router.replace('/')
In this example, we replace the current route with the root route.
router.go
This method is used to go forward or back a number of steps in the routing history.
router.go(-1)
In this example, we take a step back.
router.back
This method is used to take a step back, equivalent to router.go(-1)
.
router.back()
In this example, we take a step back.
router.forward
This method is used to advance one step, equivalent to router.go(1)
.
router.forward()
In this example, we step forward.
router.currentRoute
This property returns the current route object, which contains the following properties:
path
: route pathname
: route namehash
: the hash value in the URLquery
: query parameter in the URLparams
: parameter in route pathfullPath
: full URL pathmatched
: The matching record of the current route, containing one or more route record objects
Below is an example:
console.log(router.currentRoute)
// 输出:{path: "/", name: "Home", hash: "", query: {}, params: {}, fullPath: "/"}
Attributes
Ok, the following is the introduction of all properties of Vue Router and related codes and comments:
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import About from '@/components/About'
Vue.use(Router)
export default new Router({
mode: 'history', // 设置路由模式为history,会将URL中的#去掉
base: process.env.BASE_URL, // 指定应用的基路径,可以在不同的域名下使用相同的路由配置
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about/:id?',
name: 'About',
component: About,
props: true // 将路由参数作为组件的props传递给组件
},
{
path: '/login',
name: 'Login',
component: () => import('@/components/Login.vue') // 使用懒加载,只有访问该路由时才会加载该组件
},
{
path: '/404',
name: 'NotFound',
component: () => import('@/components/NotFound.vue')
},
{
path: '*', // 当访问其它不存在的路由时,重定向到'/404'
redirect: '/404'
}
],
scrollBehavior (to, from, savedPosition) {
// 当切换路由时,返回页面顶部
return {
x: 0, y: 0 }
}
})
Notes:
1. Import Vue Router in the Vue component and use it in the Vue instance.
2. Create a new Vue Router that contains multiple routing objects.
3. mode
The attribute is used to specify the routing mode, there are two optional values, ' hash
' and ' history
', the default is ' hash
'. The ' hash
' pattern will add a # to the URL, while the ' history
' pattern will remove the # from the URL #
.
4. base
The attribute is used to specify the base path of the application, and the same routing configuration can be used under different domain names.
5. routes
Attributes are used to define multiple routing objects.
6. The properties in the routing object path
are used to specify the routing path.
7. The property in the route object name
is used to specify the route name.
8. The attributes in the route object component
are used to specify the component corresponding to the route.
9. The attributes in the route object props
are used to specify the route parameters props
passed to the component as components.
10. Using lazy loading can improve the performance of the application, and the component will only be loaded when the route is accessed.
11. Redirect to '/404' when accessing other non-existent routes.
12. scrollBehavior
The attribute is used to specify how the page scrolls when the route is switched. In this function, you can specify where to return.
some common usage
Routing lazy loading
When the application is large, we need to consider performance issues. One way to optimize this is to split the application into smaller chunks and load those chunks dynamically when needed, this is known as lazy loading. In Vue Router, using lazy loading is very simple, just return the component as a function.
const Foo = () => import(/* webpackChunkName: "foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "bar" */ './Bar.vue')
const routes = [
{
path: '/foo',
name: 'Foo',
component: Foo
},
{
path: '/bar',
name: 'Bar',
component: Bar
}
]
In this example, we used import()
functions to dynamically load components. Note that import()
the function returns a Promise object, so we can use then()
methods to handle logic after the component loads.
routing meta information
Routing meta information refers to some additional information defined in the routing configuration, such as page title, page description, page keywords, etc. This information can be used during routing switching.
const routes = [
{
path: '/',
name: 'Home',
component: Home,
meta: {
title: '首页',
description: '这是首页',
keywords: '首页,Vue,路由'
}
},
{
path: '/about',
name: 'About',
component: About,
meta: {
title: '关于我们',
description: '这是关于我们',
keywords: '关于我们,Vue,路由'
}
}
]
In this example, we define three meta-information in the routing configuration: title
, , description
and keywords
. We can use this information to dynamically modify the page's title, description, and keywords when routing switches.
router.beforeEach((to, from, next) => {
const meta = to.meta
if (meta.title) {
document.title = meta.title
}
if (meta.description) {
const description = document.querySelector('meta[name="description"]')
description.setAttribute('content', meta.description)
}
if (meta.keywords) {
const keywords = document.querySelector('meta[name="keywords"]')
keywords.setAttribute('content', meta.keywords)
}
next()
})
In this example, we beforeEach()
get the meta information of the current route in the method, and dynamically modify the title, description and keywords of the page according to the meta information.
Route nesting
Route nesting refers to nesting a route within another route. In Vue Router, we can realize route nesting by configuring sub-routes.
const routes = [
{
path: '/',
name: 'Home',
component: Home,
children: [
{
path: 'about',
name: 'About',
component: About
},
{
path: 'contact',
name: 'Contact',
component: Contact
}
]
}
]
In this example, we have nested two sub-routes inside the root route: /about
and /contact
. In components, we can use <router-view>
components to display the components corresponding to sub-routes. For example:
<template>
<div>
<h1>Home</h1>
<router-view></router-view>
</div>
</template>
In this example, we use the component in the Home component <router-view>
to display the corresponding component of the child route.
named route
Naming a route means giving the route a name in the route configuration for use in the code. In Vue Router, we can name
implement named routes by configuring a property for each route.
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
]
In this example, we named the two routes Home
and About
. In code, we can use these names to jump to the corresponding routes.
router.push({
name: 'Home' })
In this example, we jump to Home
a route by name.
dynamic routing
Dynamic routing refers to using parameters in the routing path to match multiple routes. In Vue Router, we can use colons in routing configuration :
to define dynamic parameters.
const routes = [
{
path: '/user/:id',
name: 'User',
component: User
}
]
In this example, we define a dynamic route /user/:id
with :id
dynamic parameters. In the component, we can $route.params.id
get the value of the dynamic parameter by.
<template>
<div>
<h1>User {
{
$route.params.id }}</h1>
</div>
</template>
In this example, we define a dynamic route /user/:id
with :id
dynamic parameters. In the component, we can $route.params.id
get the value of the dynamic parameter by.
<template>
<div>
<h1>User {
{
$route.params.id }}</h1>
</div>
</template>
In this example, we display the value of a dynamic parameter in the User component.
Route navigation with parameters
After using the parameter in the routing path, we can $route.params
get the value of the parameter by . In code, we can use params
attributes to pass parameters.
router.push({
name: 'User', params: {
id: 123 } })
In this example, we set the value of params
the parameter to via the attribute , and then jump to the route.id
123
User
Redirects and Alias Routing
Redirect refers to redirecting a route to another route, which can be a string or a route configuration object. In Vue Router, we can define redirect routes using attributes in the route configuration redirect
.
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import About from '@/components/About'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
// 设置别名为info
alias: '/info',
name: 'About',
component: About
},
{
path: '/old-about',
// 重定向到/about
redirect: '/about'
}
]
})
Notes:
1. Import Vue Router in the Vue component and use it in the Vue instance.
2. Create a new Vue Router that contains multiple routing objects.
3. The first routing object is the root path '/', pointing to the Home component.
4. The second routing object has a path of '/about', points to the About component, and sets the alias to '/info'. When accessing '/info', it will redirect to '/about'.
5. The third routing object is the path '/old-about', which will redirect the request to access the path to '/about'.