Vue Router 是 Vue.js (opens new window)官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:
组件支持用户在具有路由功能的应用中 (点击) 导航。 通过 to 属性指定目标地址,默认渲染成带有正确链接的 a 标签.
<router-link to="/user">router-link>
- // 字符串
- router.push('home')
-
- // 对象
- router.push({ path: 'home' })
-
- // 命名的路由(后续参数通过this.$router.params获取)
- router.push({ name: 'user', params: { userId: '123' }})
-
- // 带查询参数,变成 /register?plan=private(后续参数通过this.$router.query获取)
- router.push({ path: 'user', query: { userId: '123' }})
与router.push方法类似,通过替换历史堆栈中的当前路由,以编程方式导航到一个新的 URL。
返回路由地址的标准化版本。
const url = router.resolve({ path: 'user', query: { userId: '123' }})
- // 在浏览器记录中前进一步,等同于 history.forward()
- router.go(1)
-
- // 后退一步记录,等同于 history.back()
- router.go(-1)
-
- // 前进 3 步记录
- router.go(3)
-
- // 如果 history 记录不够用,那就默默地失败呗
- router.go(-100)
- router.go(100)
导航守卫包含:
路由懒加载可以实现在访问的时候去加载对应的组件,并且通过懒加载的方式实现代码的分包
- const router = new VueRouter({
- routes: [{ path: '/foo', component: () => import('./Foo.vue') }]
- })
- 1. 下载vue-router依赖
- 2. 编写路由配置,全局注入router
- 3. 在vue实例上进行挂载
- 4. 使用router-view用于承载页面
官方文档 https://router.vuejs.org/zh/guide/migration/index.html
- const router = new VueRouter({
- routes // (缩写) 相当于 routes: routes
- })
-
- // 4.x
- const router = VueRouter.createRouter({
- routes, // `routes: routes` 的缩写
- })
- // 3.x
- const router = new VueRouter({
- mode: 'history', // mode: 'hash'
- routes: [...]
- })
-
- // 4.x
- import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
- const router = createRouter({
- history: createWebHashHistory(), // history: createWebHistory()
- routes,
- })
- // 3.x
- new Vue({
- router,
- render: h => h(App),
- }).$mount('#app')
-
- // 4.x
- createApp(App).use(router).mount('#app')