1.当咱们有多个页面的时候 ,咱们须要使用路由,将组件(components)映射到路由(routes),而后告诉 vue-router 在哪里渲染它们。html
简单的路由
const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ] // 3. 建立 router 实例,而后传 `routes` 配置 // 你还能够传别的配置参数, 不过先这么简单着吧。 const router = new VueRouter({ routes // (缩写)至关于 routes: routes }) // 4. 建立和挂载根实例。 // 记得要经过 router 配置参数注入路由, // 从而让整个应用都有路由功能 const app = new Vue({ router }).$mount('#app')
动态路由
一个『路径参数』使用冒号 : 标记。当匹配到一个路由时,参数值会被设置到 this.$route.params,能够在每一个组件内使用。因而,咱们能够更新 User 的模板,输出当前用户的 ID:
const User = { template: '<div>User</div>' } const router = new VueRouter({ routes: [ // 动态路径参数 以冒号开头 { path: '/user/:id', component: User } ] })
潜套路由
const router = new VueRouter({ routes: [ { path: '/user/:id', component: User, children: [ { // 当 /user/:id/profile 匹配成功, // UserProfile 会被渲染在 User 的 <router-view> 中 path: 'profile', component: UserProfile }, { // 当 /user/:id/posts 匹配成功 // UserPosts 会被渲染在 User 的 <router-view> 中 path: 'posts', component: UserPosts } ] } ] })
子节点的router 会渲染到父节点User router-view 里面vue
router.push、 router.replace 和 router.go
想要导航到不一样的 URL,则使用 router.push 方法。这个方法会向 history 栈添加一个新的记录,因此,当用户点击浏览器后退按钮时,则回到以前的 URL。vue-router
router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link> router.push({ name: 'user', params: { userId: 123 }})
一个 layout 布局展现api
<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> const router = new VueRouter({ routes: [ { path: '/', components: { default: Foo, a: Bar, b: Baz } } ] })
命名视图中咱们须要注意的地方,在props路由传值上面 对于包含命名视图的路由,你必须分别为每一个命名视图添加 props
选项浏览器
const User = { props: ['id'], template: '<div>User {{ id }}</div>' } const router = new VueRouter({ routes: [ { path: '/user/:id', component: User, props: true }, // 对于包含命名视图的路由,你必须分别为每一个命名视图添加 `props` 选项: { path: '/user/:id', components: { default: User, sidebar: Sidebar }, props: { default: true, sidebar: false } } ] })
路由的配置 declare type RouteConfig = { path: string; component?: Component; name?: string; // 命名路由 components?: { [name: string]: Component }; // 命名视图组件 redirect?: string | Location | Function; props?: boolean | string | Function; alias?: string | Array<string>; children?: Array<RouteConfig>; // 嵌套路由 beforeEnter?: (to: Route, from: Route, next: Function) => void; meta?: any; // 2.6.0+ caseSensitive?: boolean; // 匹配规则是否大小写敏感?(默认值:false) pathToRegexpOptions?: Object; // 编译正则的选项 }
后面实际应用中,在补充一下文档----目前都是看官方文档app