路由

1
2
<router-link to="/foo">Go to Foo</router-link>
<router-view></router-view>
1
2
3
4
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]

动态路由匹配

1
2
3
4
5
6
7
8
9
routes: [
// 动态路径参数 以冒号开头 id 和 post_id 是同级并列的
{ path: '/User/:id/post/:post_id', component: User }
]
// 模板
const User = {
template: '<div>User {{ $route.params.id }} Post_id {{ $route.params.post_id }}</div>'
}

你可以在一个路由中设置多段『路径参数』,对应的值都会设置到 $route.params 中。例如:

模式 匹配路径 $route.params
/user/:username /user/evan { username: 'evan' }
/user/:username/post/:post_id /user/evan/post/123 { username: 'evan', post_id: 123 }

嵌套路由

以 / 开头的嵌套路径会被当作根路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
routes: [
{
path: '/User/:id/post/:post_id',
name: 'User',
component: User,
children: [
{
path: '',
component: UserHome // 默认匹配
},
{
path: 'profile',
component: UserProfile
},
{
path: 'posts',
component: UserPosts
}
]
}
]
1
2
<router-link to="/User/Shang/post/1/Profile">Go to User ProFile</router-link>
<router-link to="/User/Xin/post/2/Posts">Go to User Posts</router-link>

编程式的导航

声明式 编程式
<router-link :to="..."> router.push(...)
1
<router-link :to="{path: '/Hello'}">Go to Hello</router-link>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 字符串
router.push('home')
// 对象
router.push({ path: 'home' })
// 命名的路由
router.push({ name: 'user', params: { userId: 123 }})
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
methods: {
testPush () {
// this.$router.push({ path: '/Hello' }) 无参数第一个必须为path
this.$router.push({name: 'Hello', params: {userId: 123}}) // 有参数第一个必须为name
// 有无参数必须和路由定义中统一 (path: '/Hello/:userId',)
},
testReplace () {
this.$router.replace({name: 'Hello', params: {userId: 123}})
},
testGo (n) {
this.$router.go(n)
}
}

命名路由

1
2
3
4
5
6
7
routes: [
{
path: '/user/:userId',
name: 'user',
component: User
}
]
1
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

这跟代码调用 router.push() 是一回事:

1
router.push({ name: 'user', params: { userId: 123 }})

命名视图

默认为 default

1
2
3
<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>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
path: '/',
components: {
default: Hello,
a: UserProfile,
b: UserPosts
}
},
{
path: '/other',
components: {
default: UserPosts,
a: UserProfile,
b: Hello
}
},

重定向

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 重定向的 字符串路径/路径对象
}}
]
})

query相当于在URL后面拼接参数,可以用 this.$route.query.num 读取

别名