路由的概念来自于后端,前端没有正真的路由,仅仅是模拟实现。

为什么要使用路由?

因为当我们的前端项目比较复杂、页面文件较多,通过传统 a 标签跳转同步页面,会导致页面白屏、闪白、响应不及时,用户体验较差、代码不易维护。
通过解析浏览器地址栏参数,根据路由参数,局部重绘页面视图,结合 innerHTML、appendChild,异步操作请求数据来局部更新我们的页面。

分类

  • hash 哈希(/#/<路由名称>)不会向服务器发起请求
  • history 历史 (/<路由名称>) 会向服务器发起请求

路由参数

| name | 路由名称 |

| |
| —- | ——– |
| path | 路由路径 |

|
| component | 路由组件 |

|
| meta | 路由信息对象 |

|
| alias | 路由别名 |

|
| redirect | 路由重定向 |

|
| * | 通配符 |

|

配置路由

项目较大或者页面较多,为了提升组件加载速度,通过按需加载路由组件提升性能

router/routes.js

1
2
3
4
5
6
7
8
const routes = [
{
path: "/",
name: "default",
component: () => import("@/views/xxx.vue"),
},
];
export default routes;

router/index.js

1
2
3
4
5
6
7
8
9
import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
Vue.use(VueRouter);

export default new VueRouter({
mode: "history",
routes,
});

路由 404

router/routes.js

1
2
3
4
5
6
7
8
9
{
path: "/404",
name: "notFound",
component: () => import("@/views/notFound"),
},
{
path: "*",
redirect: "/404",
},

全局导航守

1
2
3
4
5
6
7
8
const router = new VueRouter();

router.beforeEach((to, from, next) => {
next();
});
router.afterEach((to, from, next) => {
next();
});

路由独享的守卫 beforeEnter

router/routes.js

1
2
3
4
5
6
7
8
9
const routes = [
{
path: "/foo",
component: () => import("@/views/somepage.vue"),
//方法与全局前置守卫的方法参数是一样的
beforeEnter: function (to, from, next) {},
afterEnter: function () {},
},
];

组件内的守卫

views/somepage.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script>
export default {
//在渲染该组件的对应路由被confirm前调用
//不能获取组件实例 this
//因为当守卫执行前,组件实例还没被创建
beforeRouteEnter(to, from, next) {
console.log(to, from, next);
next();
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
},
beforeRouteUpdate(to, from, next) {
console.log(to, from, next);
next();
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
},
beforeRouteLeave(to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
console.log(to, from, next);
next();
},
}
</script>

路由传参

  • path+query
  • name+params
  • 动态路由传参