router-link 和 router-view组件编程
<div id="app"> <h1>Hello App!</h1> <p> <!-- 使用 router-link 组件来导航. --> <!-- 经过传入 `to` 属性指定连接. --> <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 --> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> <!-- 命名的路由+动态路由 --> <router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link> </p> <!-- 路由出口 --> <!-- 路由匹配到的组件将渲染在这里 --> <router-view></router-view> </div>
2.路由配置app
a.动态路由 // 动态路径参数 以冒号开头 { path: '/user/:id', component: User }
b.嵌套路由
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 }] }] })
c.命名路由 加了一个name属性 d.命名视图 有时候想同时 (同级) 展现多个视图,而不是嵌套展现,例如建立一个布局,有 sidebar (侧导航) 和 main (主内容) 两个视图,这个时候命名视图就派上用场了。 <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>
3.JS操做路由异步
声明式: <router-link :to="..."> 编程式: router.push(...) const userId = '123' router.push({ name: 'user', params: { userId }}) // -> /user/123 router.push({ path: `/user/${userId}` }) // -> /user/123// 这里的 params 不生效 router.push({ path: '/user', params: { userId }}) // -> /user 声明式: <router-link :to="..." replace> 编程式: router.replace(...) 跟 router.push 很像,惟一的不一样就是,它不会向 history 添加新记录,而是跟它的方法名同样 —— 替换掉当前的 history 记录
4.重定向和别名ide
重定向: { path: '/a', redirect: '/b' } { path: '/a', redirect: { name: 'foo' }} { path: '/a', redirect: to => { // 方法接收 目标路由 做为参数 // return 重定向的 字符串路径/路径对象 }} 别名: “重定向”的意思是,当用户访问 /a时,URL 将会被替换成 /b,而后匹配路由为 /b,那么“别名”又是什么呢? /a 的别名是 /b,意味着,当用户访问 /b 时,URL 会保持为 /b,可是路由匹配则为 /a,就像用户访问 /a 同样。 { path: '/a', component: A, alias: '/b' }
完整的导航解析流程函数
1. 导航被触发。 2. 在失活的组件里调用离开守卫。 3. 调用全局的 beforeEach 守卫。 4. 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。 5. 在路由配置里调用 beforeEnter。 6. 解析异步路由组件。 7. 在被激活的组件里调用 beforeRouteEnter。 8. 调用全局的 beforeResolve 守卫 (2.5+)。 9. 导航被确认。 10. 调用全局的 afterEach 钩子。 11. 触发 DOM 更新。 12. 用建立好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。