const router = new VueRouter({ routes: [ // 动态路径参数 以冒号开头 { path: '/user/:id', component: User } ] })
当匹配到一个路由时,参数值会被设置到
this.$route.params
watch: { '$route' (to, from) { // 对路由变化做出响应... } }
beforeRouteUpdate (to, from, next) { // react to route changes... // don't forget to call next()
// 在当前路由改变,可是该组件被复用时调用 (动态路由) // 举例来讲,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候, // 因为会渲染一样的 Foo 组件,所以组件实例会被复用。而这个钩子就会在这个状况下被调用。 // 能够访问组件实例 `this`
}
{ // 会匹配全部路径 path: '*' } { // 会匹配以 `/user-` 开头的任意路径 path: '/user-*' }
当使用一个通配符时,$route.params
内会自动添加一个名为 pathMatch
参数。它包含了 URL 经过通配符被匹配的部分html
router.push
方法。这个方法会向 history 栈添加一个新的记录,因此,当用户点击浏览器后退按钮时,则回到以前的 URL。vue
// 字符串 router.push('home') // 对象 router.push({ path: 'home' }) // 命名的路由 router.push({ name: 'user', params: { userId: '123' }}) // 带查询参数,变成 /register?plan=private router.push({ path: 'register', query: { plan: 'private' }})
注意:若是提供了 path
,params
会被忽略,上述例子中的 query
并不属于这种状况。取而代之的是下面例子的作法,你须要提供路由的 name
或手写完整的带有参数的 path
:react
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-link
组件的 to
属性。编程
注意: 若是目的地和当前路由相同,只有参数发生了改变 (好比从一个用户资料到另外一个 /users/1
-> /users/2
),你须要使用 beforeRouteUpdate
来响应这个变化 (好比抓取用户信息)。浏览器
若是 router-view
没有设置名字,那么默认为 default
ide
<router-link to="/">/</router-link>
<router-link to="/other">/other</router-link>ui
<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> 一个视图使用一个组件渲染,所以对于同个路由,多个视图就须要多个组件。确保正确使用 components 配置 (带上 s): const router = new VueRouter({ routes: [ { path: '/', components: { default: Foo, a: Bar, b: Baz } } ] })
重定向也是经过 routes 配置来完成,下面例子是从 /a 重定向到 /b: const router = new VueRouter({ routes: [ { path: '/a', redirect: '/b' } ] }) 重定向的目标也能够是一个命名的路由: const router = new VueRouter({ routes: [ { path: '/a', redirect: { name: 'foo' }} ] }) 甚至是一个方法,动态返回重定向目标: const router = new VueRouter({ routes: [ { path: '/a', redirect: to => { // 方法接收 目标路由 做为参数 // return 重定向的 字符串路径/路径对象 }} ] }) 注意导航守卫并无应用在跳转路由上,而仅仅应用在其目标上。在下面这个例子中,为 /a 路由添加一个 beforeEach 或 beforeLeave 守卫并不会有任何效果。
const router = new VueRouter({ routes: [ { path: '/a', component: A, alias: '/b' } ] })