路由
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: [ { 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 }})
router.push({ path: 'register', query: { plan: 'private' }})
methods: { testPush () { this.$router.push({name: 'Hello', params: {userId: 123}}) }, 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 读取
别名