传递参数
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
routes: [
// dynamic segments start with a colon
{ path: '/user/:id', component: User }
]
})
router | path | $ route.params |
---|---|---|
/ user /:用户名 | /user/evan | { username: 'evan' } |
/ user /:用户名/ post /:post_id | / user / evan / post / 123 | { username: 'evan', post_id: '123' } |
const User = {
template: '...',
watch: {
$route(to, from) {
// react to route changes...
}
}
}
传参中的props
const User = {
props: ['id'],
template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },
// for routes with named views, you have to define the `props` option for each named view:
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
})
嵌套路径
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User,
children: [
{
// UserProfile will be rendered inside User's <router-view>
// when /user/:id/profile is matched
path: 'profile',
component: UserProfile
},
{
// UserPosts will be rendered inside User's <router-view>
// when /user/:id/posts is matched
path: 'posts',
component: UserPosts
}
]
}
]
})
路由跳转
<router-link :to="...">
router.push('home')
// object
router.push({ path: 'home' })
// named route
router.push({ name: 'user', params: { userId: '123' } })
// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' } })
router.replace(location, onComplete?, onAbort?)
表现类似router.push,区别是不产生新的history,而是替换当前的地址。
routes: [
{ path: '/a', redirect: { name: 'foo' }}
]
routes: [
{ path: '/a', redirect: '/b' }
]
历史记录跳转
router.go(n)
router.go(1)
// go back by one record, the same as history.back()
router.go(-1)
// go forward by 3 records
router.go(3)
// fails silently if there aren't that many records.
router.go(-100)
router.go(100)
网友评论