<router-link to="/foo">Go to Foo</router-link>
<router-view></router-view>
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
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 } |
以 / 开头的嵌套路径会被当作根路径
routes: [
{
path: '/User/:id/post/:post_id',
name: 'User',
component: User,
children: [
{
path: '',
component: UserHome // 默认匹配
},
{
path: 'profile',
component: UserProfile
},
{
path: 'posts',
component: UserPosts
}
]
}
]
<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(...) |
<router-link :to="{path: '/Hello'}">Go to Hello</router-link>
// 字符串
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)
}
}
routes: [
{
path: '/user/:userId',
name: 'user',
component: User
}
]
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
这跟代码调用 router.push()
是一回事:
router.push({ name: 'user', params: { userId: 123 }})
默认为 default
<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>
{
path: '/',
components: {
default: Hello,
a: UserProfile,
b: UserPosts
}
},
{
path: '/other',
components: {
default: UserPosts,
a: UserProfile,
b: Hello
}
},
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 读取