官方文档:https://router.vuejs.org/zh/guide/#html
一、起步
HTML
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- 使用 router-link 组件来导航. -->
<!-- 通过传入 `to` 属性指定链接. -->
<!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
JavaScript
// 0. 如果使用模块化机制编程,导入Vue和VueRouter,要调用 Vue.use(VueRouter)
// 1. 定义 (路由) 组件。
// 可以从其他文件 import 进来
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
// 2. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是通过 Vue.extend() 创建的组件构造器,
// 或者,只是一个组件配置对象。
const
// 3. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数
const router = new VueRouter({
routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
})
// 4. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
const app = new Vue({
router
}).$mount('#app')
// 现在,应用已经启动了!
注意:通过注入路由器,我们可以在任何组件内通过
this.$router
访问路由器,也可以通过this.$route
访问当前路由:
二、动态路由匹配
/user/foo
和 /user/bar
都将映射到相同的路由,可以通过$route.params
获取
const User = {
template: '<div>User</div>'
}
const router = new VueRouter({
routes: [
// 动态路径参数 以冒号开头
{ path: '/user/:id', component: User }
]
})
响应路由参数的变化
从 /user/foo
导航到 /user/bar
,原来的组件实例会被复用。因为两个路由都渲染同个组件,比起销毁再创建,复用则显得更加高效。不过,这也意味着组件的生命周期钩子不会再被调用。
- 复用组件时,想对路由参数的变化作出响应的话,你可以简单地 watch (监测变化)
$route
对象或者使用 2.2 中引入的beforeRouteUpdate
导航守卫:
const User = {
template: '...',
watch: {
$route(to, from) {
// 对路由变化作出响应...
}
},
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
}
捕获所有路由或 404 Not found 路由
常规参数只会匹配被 /
分隔的 URL 片段中的字符。如果想匹配任意路径,我们可以使用通配符 (*)
{
// 会匹配所有路径
path: '*'
}
{
// 会匹配以 `/user-` 开头的任意路径
path: '/user-*'
}
三、嵌套路由
一个被渲染组件同样可以包含自己的嵌套 。例如,在 User
组件的模板添加一个 <router-view>
,要在嵌套的出口中渲染组件,需要在 VueRouter
的参数中使用 children
配置:
const User = {
template: `
<div class="user">
<h2>User {{ $route.params.id }}</h2>
<router-view></router-view>
</div>
`
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User,
children: [
{
// 当 /user/:id/profile 匹配成功,
// UserProfile 会被渲染在 User 的 <router-view> 中
path: 'profile',
component: UserProfile
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 会被渲染在 User 的 <router-view> 中
path: 'posts',
component: UserPosts
},
// 当 /user/:id 匹配成功,
// UserHome 会被渲染在 User 的 <router-view> 中
{ path: '', component: UserHome },
]
}
]
})
四、编程式的导航
router.push(location, onComplete?, onAbort?)
- 声明式:
<router-link :to="...">
- 编程式:
router.push(...)
注意:如果提供了 path
,params
会被忽略,下述例子中的 query
并不属于这种情况。取而代之的是下面例子的做法,你需要提供路由的 name
或手写完整的带有参数的 path
:
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 这里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user
router.replace(location, onComplete?, onAbort?)
替换掉当前的 history 记录
- 声明式:
<router-link :to="..." replace>
- 编程式:
router.replace(...)
router.go(n)
这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)
五、命名视图
在界面中拥有多个单独命名的视图,而不是只有一个单独的出口。如果 router-view
没有设置名字,那么默认为 default
。一个视图使用一个组件渲染,因此对于同个路由,多个视图就需要多个组件。确保正确使用 components
配置 (带上 s):
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>
const router = new VueRouter({
routes: [
{
path: '/',
components: {
default: Foo,
a: Bar,
b: Baz
}
}
]
})
六、重定向和别名
重定向(redirect)
“重定向”的意思是,当用户访问 /a
时,URL 将会被替换成 /b
,然后匹配路由为 /b
const router = new VueRouter({
routes: [
// 从 /a 重定向到 /b
{ path: '/a', redirect: '/b' },
// 重定向的目标也可以是一个命名的路由
{ path: '/a', redirect: { name: 'foo' }},
// 甚至是一个方法,动态返回重定向目标
{ path: '/a', redirect: to => {
// 方法接收 目标路由 作为参数
// return 重定向的 字符串路径/路径对象
}}
]
})
别名(alias)
/a
的别名是 /b
,意味着,当用户访问 /b
时,URL 会保持为 /b
,但是路由匹配则为 /a
,就像用户访问 /a
一样。
const router = new VueRouter({
routes: [
{ path: '/a', component: A, alias: '/b' }
]
})
七、路由组件传参
使用 props
将组件和路由解耦取代与 $route
的耦合
const User = {
props: ['id'],
// template: '<div>User {{ $route.params.id }}</div>'
template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },
// 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
})
函数模式
你可以创建一个函数返回 props
。这样你便可以将参数转换成另一种类型,将静态值与基于路由的值结合等等。
const router = new VueRouter({
routes: [
{ path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) }
]
})
URL
/search?q=vue
会将{query: 'vue'}
作为属性传递给SearchUser
组件
八、HTML5 History 模式
如要使用history模式,则需在后端服务器进行相应的配置:
基于 Node.js 的 Express:
npm install --save connect-history-api-fallback
var history = require('connect-history-api-fallback');
var express = require('express');
var app = express();
app.use(history());
警告
给个警告,因为这么做以后,你的服务器就不再返回 404 错误页面,因为对于所有路径都会返回 index.html
文件。为了避免这种情况,你应该在 Vue 应用里面覆盖所有的路由情况,然后在给出一个 404 页面。
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '*', component: NotFoundComponent }
]
})