const router = new VueRouter({
// HTML5 History 模式(需要结合后端配置) mode:'history', routes: [
// 常规 { path:'/user', component:User },
// 动态路由匹配
{ path: '*', // 匹配所有路径 component: User }, { path: '/user-*', // 匹配以'/user-'开头的任意路径 component: User },
// 动态路径参数,以冒号开头
// 参数值会被设置到 this.$route.params中 { path: '/user/:id', component: User }, { path: '/user/:username/post/:post_id', component: User }, // 嵌套路由 { path:'/user/:id', component: User, children: [ // 当 /user/:id 匹配成功, // UserHome 会被渲染在 User 的 <router-view> 中 { path:'', component: UserHome }, // 当 /user/:id/profile 匹配成功, // UserProfile 会被渲染在 User 的 <router-view> 中 { path:'profile', component: UserProfile }, // 当 /user/:id/posts 匹配成功 // UserPosts 会被渲染在 User 的 <router-view> 中 { path:'posts', component: UserPosts } ] }, // 命名路由 { path: '/user/:userId', name: 'user', component: User }, // 命名视图 { path: '/user', name: 'user', components: { default:User, // 当router-view没有设置名称时(属性name),默认为default bar:Bar, // 当router-view的 name 设置为 bar 时 foo:Foo // 当router-view的 name 设置为 foo 时 } }, // 嵌套命名视图 { path: '/user', name: 'user', children: [ { path:'profile', component: UserProfile }, { path:'posts', components: { default:UserPosts, bar:Bar } } ] }, // 重定向 { path:'/a', redirect:'/b' }, // 重定向的目标也可以是一个命名的路由 { path:'/a', redirect:{ name:'foo' } }, // 重定向的目标甚至是一个方法 { path:'/a', redirect:to => { // 方法接收 目标路由 作为参数 // return 重定向的 字符串路径/路径对象 } }, // 别名 { path:'/a', alias:'/b', component:A }, // 路由组件传参 // props解耦
// 布尔模式 { path:'/user/:id', props:true, component:User }, // 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项 { path:'/user/:id', component:{ default:User, bar:Bar }, props:{ default:true, bar:false }, }, // 对象模式 // 如果 props 是一个对象,它会被按原样设置为组件属性。当 props 是静态的时候有用。 { path:'/user/from-newsletter', props:{ newsletterPopup:false }, component:User }, // 函数模式 // 创建一个函数返回 props。这样你便可以将参数转换成另一种类型,将静态值与基于路由的值结合等等 { path:'/search', props:(route) => ({query:route.query.q}), component:SearchUser },
// 路由元信息
// 需要遍历 $route.matched 来检查路由记录中的 meta 字段
{
path:'/user',
component:User,
meta:{
requiresAuth:true
}
},
// 路由懒加载
// 组件按组分块
// 有时候我们想把某个路由下的所有组件都打包在同个异步块 (chunk) 中。
// 只需要使用 命名 chunk,一个特殊的注释语法来提供 chunk name
{
path:'/user',
component: () => import(/* webpackChunkName: "user" */ './User.vue')
} ],
// 滚动行为
// 此功能只支持 history.pushState 的浏览器
// 访方法返回滚动位置的对象信息:
// {x:number,y:number}
// {selector:string, offset?:{x:number,y:number}}scrollBehavior(to,from,savedPosition){
// return 期望滚动到哪个位置
// return {x:0,y:0}
}
})