经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
Vue.js?前端路由和异步组件介绍
来源:jb51  时间:2022/9/15 9:09:00  对本文有异议

文章目标

P6

  • 针对 react/vue 能够根据业务需求口喷 router 的关键配置,包括但不限于:路由的匹配规则、路由守卫、路由分层等;
  • 能够描述清楚 history 的主要模式,知道 history 和 router 的边界;

P6+ ~ P7

  • 在没有路由的情况下,也可以根据也无需求,实现一个简单的路由;
  • 读过 router 底层的源码,不要求每行都读,可以口喷关键代码即可;

一、背景

远古时期,当时前后端还是不分离的,路由全部都是由服务端控制的,前端代码和服务端代码过度融合在一起。

客户端 --> 前端发起 http 请求 --> 服务端 --> url 路径去匹配不同的路由 --> 返回不同的数据。

这种方式的缺点和优点都非常明显:

  • 优点:因为直接返回一个 html,渲染了页面结构。SEO 的效果非常好,首屏时间特别快;
    • 在浏览器输入一个 url 开始到页面任意元素加载出来/渲染出来 --> 首屏时间;
  • 缺点:前端代码和服务端代码过度融合在一起,开发协同非常的乱。服务器压力大,因为把构建 html 的工作放在的服务端;

后来 ...随之 ajax 的流行,异步数据请求可以在浏览器不刷新的情况下进行。

后来 ...出现了更高级的体验 —— 单页应用

  •  --> HTML 文件
  • 单页 --> 单个 HTML 文件

在单页应用中,不仅在页面中的交互是不刷新页面的,就连页面跳转也都是不刷新页面的。

单页应用的特点:

  • 页面中的交互是不刷新的页面的,比如点击按钮,比如点击出现一个弹窗;
  • 多个页面间的交互,不需要刷新页面(a/b/ca-> b -> c);加载过的公共资源,无需再重复加载;

而支持起单页应用这种特性的,就是 前端路由

二、前端路由特性

前端路由的需求是什么?

  • 根据不同的 url 渲染不同内容;
  • 不刷新页面;

也就是可以在改变 url 的前提下,保证页面不刷新。

三、面试!!!

Hash 路由和 History 路由的区别?

  • hash 有 #history 没有 #
  • hash 的 # 部分内容不会给服务端,主要一般是用于锚点, history 的所有内容都会给服务端;
  • hash 路由是不支持 SSR 的,history 路由是可以的;
  • hash 通过 hashchange 监听变化,history 通过 popstate 监听变化;

四、Hash 原理及实现

1、特性

hash 的出现满足了这个需求,他有以下几种特征:

  • url 中带有一个 # 符号,但是 # 只是浏览器端/客户端的状态,不会传递给服务端;
    • 客户端路由地址 www.baidu.com/#/user --> 通过 http 请求 --> 服务端接收到的 www.baidu.com/
    • 客户端路由地址 www.baidu.com/#/list/detail/1 --> 通过 http 请求 --> 服务端接收到的 www.baidu.com/
  • hash 值的更改,不会导致页面的刷新;
  1. location.hash = '#aaa';
  2. location.hash = '#bbb';
  3. // 从 #aaa 到 #bbb,页面是不会刷新的
  • 不同 url 会渲染不同的页面;
  • hash 值的更改,会在浏览器的访问历史中添加一条记录,所以我们才可以通过浏览器的返回、前进按钮来控制 hash 的切换;
  • hash 值的更改,会触发 hashchange 事件;
  1. location.hash = '#aaa';
  2. location.hash = '#bbb';
  3.  
  4. window.addEventLisenter('hashchange', () => {});

2、如何更改 hash

我们同样有两种方式来控制 hash 的变化:

  • location.hash 的方式:
  1. location.hash = '#aaa';
  2. location.hash = '#bbb';
  • html 标签的方式:
  1. <a href="#user" rel="external nofollow" > 点击跳转到 user </a>
  2.  
  3. <!-- 等同于下面的写法 -->
  4. location.hash = '#user';

3、手动实现一个基于 hash 的路由

  • ./index.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. <link rel="stylesheet" href="./index.css" rel="external nofollow" />
  9. </head>
  10. <body>
  11. <div class="container">
  12. <a href="#gray" rel="external nofollow" >灰色</a>
  13. <a href="#green" rel="external nofollow" >绿色</a>
  14. <a href="#" rel="external nofollow" >白色</a>
  15. <button onclick="window.history.go(-1)">返回</button>
  16. </div>
  17.  
  18. <script type="text/javascript" src="index.js"></script>
  19. </body>
  20. </html>
  • ./index.css
  1. .container {
  2. width: 100%;
  3. height: 60px;
  4. display: flex;
  5. justify-content: space-around;
  6. align-items: center;
  7.  
  8. font-size: 18px;
  9. font-weight: bold;
  10.  
  11. background: black;
  12. color: white;
  13. }
  14.  
  15. a:link,
  16. a:hover,
  17. a:active,
  18. a:visited {
  19. text-decoration: none;
  20. color: white;
  21. }
  • ./index.js
  1. /*
  2. 期望看到的效果:点击三个不同的 a 标签,页面的背景颜色会随之变化
  3. */
  4. class BaseRouter {
  5. constructor() {
  6. this.routes = {}; // 存储 path 以及 callback 的对应关系
  7. this.refresh = this.refresh.bind(this); // 如果不 bind 的话,refresh 方法中的 this 指向 window
  8. // 处理页面 hash 变化,可能存在问题:页面首次进来可能是 index.html,并不会触发 hashchange 方法
  9. window.addEventListener('hashchange', this.refresh);
  10.  
  11. // 处理页面首次加载
  12. window.addEventListener('load', this.refresh);
  13. }
  14.  
  15. /**
  16. * route
  17. * @param {*} path 路由路径
  18. * @param {*} callback 回调函数
  19. */
  20. route(path, callback) {
  21. console.log('========= route 方法 ========== ', path);
  22. // 向 this.routes 存储 path 以及 callback 的对应关系
  23. this.routes[path] = callback || function () {};
  24. }
  25.  
  26. refresh() {
  27. // 刷新页面
  28. const path = `/${location.hash.slice(1) || ''}`;
  29. console.log('========= refresh 方法 ========== ', path);
  30. this.routes[path]();
  31. }
  32. }
  33.  
  34. const body = document.querySelector('body');
  35. function changeBgColor(color) {
  36. body.style.backgroundColor = color;
  37. }
  38.  
  39. const Router = new BaseRouter();
  40.  
  41. Router.route('/', () => changeBgColor('white'));
  42. Router.route('/green', () => changeBgColor('green'));
  43. Router.route('/gray', () => changeBgColor('gray'));

五、History 原理及实现

hash 有个 # 符号,不美观,服务端无法接受到 hash 路径和参数。

历史的车轮无情撵过 hash,到了 HTML5 时代,推出了 History API

1、HTML5 History 常用的 API

  1. window.history.back(); // 后退
  2.  
  3. window.history.forward(); // 前进
  4.  
  5. window.history.go(-3); // 接收 number 参数,后退 N 个页面
  6.  
  7. window.history.pushState(null, null, path);
  8.  
  9. window.history.replaceState(null, null, path);

其中最主要的两个 API 是 pushState 和 replaceState,这两个 API 都可以在不刷新页面的情况下,操作浏览器历史记录。

不同的是,pushState 会增加历史记录,replaceState 会直接替换当前历史记录。

2、pushState/replaceState 的参数

  • pushState:页面的浏览记录里添加一个历史记录;
  • replaceState:替换当前历史记录;

他们的参数是?样的,三个参数分别是:

  • state:是一个对象,是一个与指定网址相关的对象,当 popstate 事件触发的时候,该对象会传入回调函数;
  • title:新页面的标题,浏览器支持不一,建议直接使用 null
  • url:页面的新地址;

3、History 的特性

History API 有以下几个特性:

  • 没有 #
  • history.pushState() 或 history.replaceState() 不会触发 popstate 事件,这时我们需要手动触发页面渲染;
  • 可以使用 history.popstate 事件来监听 url 的变化;
  • 只有用户点击浏览器 倒退按钮 和 前进按钮,或者使用 JavaScript 调用 backforwardgo 方法时才会触发 popstate

4、面试!!!

  • pushState 时,会触发 popstate 吗?

    • pushState/replaceState 并不会触发 popstate 事件,这时我们需要手动触发页面的重新渲染;
  • 我们可以使用 popstate 来监听 url 的变化;

  • popstate 到底什么时候才能触发:

    • 点击浏览器后退按钮;
    • 点击浏览器前进按钮;
    • js 调用 back 方法;
    • js 调用 forward 方法;
    • js 调用 go 方法;

5、手动实现一个基于 History 的路由

  • ./index.html
  • ./index.css
  1. .container {
  2. width: 100%;
  3. height: 60px;
  4. display: flex;
  5. justify-content: space-around;
  6. align-items: center;
  7.  
  8. font-size: 18px;
  9. font-weight: bold;
  10.  
  11. background: black;
  12. color: white;
  13. }
  14.  
  15. a:link,
  16. a:hover,
  17. a:active,
  18. a:visited {
  19. text-decoration: none;
  20. color: white;
  21. }
  • ./index.js
  1. class BaseRouter {
  2. constructor() {
  3. this.routes = {};
  4.  
  5. // location.href; => hash 的方式
  6. console.log('location.pathname ======== ', location.pathname); // http://127.0.0.1:8080/green ==> /green
  7. this.init(location.pathname);
  8. this._bindPopState();
  9. }
  10.  
  11. init(path) {
  12. // pushState/replaceState 不会触发页面的渲染,需要我们手动触发
  13. window.history.replaceState({ path }, null, path);
  14. const cb = this.routes[path];
  15. if (cb) {
  16. cb();
  17. }
  18. }
  19.  
  20. route(path, callback) {
  21. this.routes[path] = callback || function () {};
  22. }
  23.  
  24. // ! 跳转并执行对应的 callback
  25. go(path) {
  26. // pushState/replaceState 不会触发页面的渲染,需要我们手动触发
  27. window.history.pushState({ path }, null, path);
  28. const cb = this.routes[path];
  29. if (cb) {
  30. cb();
  31. }
  32. }
  33. // ! 演示一下 popstate 事件触发后,会发生什么
  34. _bindPopState() {
  35. window.addEventListener('popstate', e => {
  36. /*
  37. 触发条件:
  38. 1、点击浏览器前进按钮
  39. 2、点击浏览器后退按钮
  40. 3、js 调用 forward 方法
  41. 4、js 调用 back 方法
  42. 5、js 调用 go 方法
  43. */
  44. console.log('popstate 触发了');
  45. const path = e.state && e.state.path;
  46. console.log('path >>> ', path);
  47. this.routes[path] && this.routes[path]();
  48. });
  49. }
  50. }
  51. const Router = new BaseRouter();
  52. const body = document.querySelector('body');
  53. const container = document.querySelector('.container');
  54.  
  55. function changeBgColor(color) {
  56. body.style.backgroundColor = color;
  57. }
  58. Router.route('/', () => changeBgColor('white'));
  59. Router.route('/gray', () => changeBgColor('gray'));
  60. Router.route('/green', () => changeBgColor('green'));
  61.  
  62. container.addEventListener('click', e => {
  63. if (e.target.tagName === 'A') {
  64. e.preventDefault();
  65. console.log(e.target.getAttribute('href')); // /gray /green 等等
  66. Router.go(e.target.getAttribute('href'));
  67. }
  68. });

六、Vue-Router

1、router 使用

使用 Vue.js,我们已经可以通过组合组件来组成应用程序,当你要把 Vue Router 添加进来,我们需要做的是,将组件(components)映射到路由(routes),然后告诉 Vue Router 在哪里渲染它们。

举个例子:

  1. <!-- 路由匹配到的组件将渲染在这里 -->
  2. <div id="app">
  3. <router-view></router-view>
  4. </div>
  1. // 如果使用模块化机制编程,导入 Vue 和 VueRouter,要调用 Vue.use(VueRouter)
  2.  
  3. // 1、定义(路由)组件
  4. // 可以从其他文件 import 进来
  5. const Foo = { template: '<div>foo</div>' };
  6. const Bar = { template: '<div>bar</div>' };
  7.  
  8. // 2、定义路由
  9. //每个路由应该映射一个组件,其中 component 可以是通过 Vue.extend() 创建的组件构造器,或者只是一个组件配置对象
  10. const routes = [
  11. { path: '/foo', component: Foo },
  12. { path: '/bar', component: Bar },
  13. ];
  14.  
  15. // 3、创建 router 实例,然后传 routes 配置
  16. const router = new VueRouter({
  17. routes,
  18. });
  19.  
  20. // 4、创建和挂载根实例
  21. // 记得要通过 router 配置参数注入路由,从而让整个应用都有路由功能
  22. const app = new Vue({
  23. router,
  24. }).$mount('#app');

2、动态路由匹配

我们经常需要把某种模式匹配到的所有路由,全部映射到同个组件,比如用户信息组件,不同用户使用同一个组件。

可以通过 $route.params.id 或者参数。

  1. const router = new VueRouter({
  2. routes: [
  3. // 动态路径参数,以冒号开头
  4. { path: '/user/:id', component: User },
  5. ],
  6. });
  7.  
  8. const User = {
  9. template: '<div>User: {{ $route.params.id }}</div>',
  10. };

3、响应路由参数的变化

复用组件时,想对 路由参数 的变化作出响应的话,可以使用 watch 或者 beforeRouteUpdate

举个例子:

  1. const User = {
  2. template: '...',
  3. watch: {
  4. $route(to, from) {
  5. // 对路由变化作出响应...
  6. },
  7. },
  8. };
  9.  
  10. const User = {
  11. template: '...',
  12. beforeRouteUpdate(to, from, next) {
  13. // 对路由变化作出响应...
  14. // don't forget to call next()
  15. },
  16. };

4、捕获所有路由或 404 Not found 路由

当时用通配符路由时,请确保路由的顺序是正确的,也就是说含有通配符的路由应该在 最后

举个例子:

5、导航守卫

vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。有多种方式植入路由导航过程中:

  • 全局的
    • 全局前置守卫:router.beforeEach
    • 全局解析守卫:router.beforeResolve
    • 全局后置钩子:router.afterEach
  • 单个路由独享的
    • 路由独享守卫:beforeEnter
  • 组件级的
    • beforeRouteEnter
    • beforeRouteUpdate
    • beforeRouteLeave

6、完整的导航解析流程

  • 导航被触发;
  • 在失活的组件里调用离开守卫(前一个组件的 beforeRouteLeave);
  • 调用全局的 beforeEach 守卫;
  • 在重用的组件里调用 beforeRouteUpdate 守卫;
  • 在路由配置里调用 beforeEnter
  • 解析异步路由组件;
  • 在被激活的组件里调用 beforeRouterEnter
  • 调用全局的 beforeResolve 守卫;
  • 导航被确认;
  • 调用全局的 afterEach 钩子;
  • 触发 DOM 更新;
  • 用创建好的实例调用 beforeRouterEnter 守卫中传给 next 的回调函数;

举个例子:

  1. // 全局
  2. const router = new VueRouter({
  3. mode: 'history',
  4. base: process.env.BASE_URL,
  5. routes,
  6. });
  7.  
  8. // 全局的导航守卫
  9. router.beforeEach((to, from, next) => {
  10. console.log(`Router.beforeEach => from=${from.path}, to=${to.path}`);
  11. // 可以设置页面的 title
  12. document.title = to.meta.title || '默认标题';
  13. // 执行下一个路由导航
  14. next();
  15. });
  16.  
  17. router.afterEach((to, from) => {
  18. console.log(`Router.afterEach => from=${from.path}, to=${to.path}`);
  19. });
  20.  
  21. // 路由独享
  22. const router = new VueRouter({
  23. routes: [
  24. {
  25. path: '/foo',
  26. component: Foo,
  27. beforeEnter: (to, from, next) => {
  28. // 配置数组里针对单个路由的导航守卫
  29. console.log(`TestComponent route config beforeEnter => from=${from.path}, to=${to.path}`);
  30. next();
  31. },
  32. },
  33. ],
  34. });
  35.  
  36. // 组件
  37. const Foo = {
  38. template: `...`,
  39. beforeRouteEnter(to, from, next) {
  40. // 在渲染该组件的对应路由被 comfirm 前调用
  41. // 不!能!获取组件实例 this,因为当守卫执行前,组件实例还没被调用
  42. },
  43. beforeRouteUpdate(to, from, next) {
  44. // 在当前路由改变,但是该组件被复用时调用
  45. // 举个例子来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候
  46. // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用
  47. // 可以访问组件实例 this
  48. },
  49. beforeRouteLeave(to, from, next) {
  50. // 导航离开该组件的对应路由时调用
  51. // 可以访问组件实例 this
  52. },
  53. };

next 必须调用:

  • next():进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed(确认的)。
  • next(false):中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。
  • next("/") 或者 next({ path: "/" }):跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。可以向 next 传递任意位置对象,且允许设置诸如 replace: truename: "home" 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。
  • next(error):如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

7、导航守卫执行顺序(面试!!!)

  • 【组件】前一个组件的 beforeRouteLeave
  • 【全局】的 router.beforeEach
    • 【组件】如果是路由参数变化,触发 beforeRouteUpdate
  • 【配置文件】里,下一个的 beforeEnter
  • 【组件】内部声明的 beforeRouteEnter
  • 【全局】的 router.afterEach

8、滚动行为(面试!!!)

vue-router 里面,怎么记住前一个页面的滚动条的位置???

使用前端路由,当切换到新路由时,想要页面滚动到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。

Vue-router 能做到,而且更好,它让你可以自定义路由切换时页面如何滚动。

【注意】:这个功能只在支持 history.pushState 的浏览器中可用。

scrollBehavior 生效的条件:

  • 浏览器支持 history API
  • 页面间的交互是通过 goforwardback 或者 浏览器的前进/返回按钮
  1. window.history.back(); // 后退
  2. window.history.forward(); // 前进
  3. window.history.go(-3); // 接收 number 参数,后退 N 个页面

举个例子

  1. // 1. 记住:手动点击浏览器返回或者前进按钮,记住滚动条的位置,基于 history API 的,其中包括:go、back、forward、手动点击浏览器返回或者前进按钮
  2. // 2. 没记住:router-link,并没有记住滚动条的位置
  3.  
  4. const router = new VueRouter({
  5. mode: 'history',
  6. base: process.env.BASE_URL,
  7. routes,
  8. scrollBehavior: (to, from, savedPosition) => {
  9. console.log(savedPosition); // 已保存的位置信息
  10. return savedPosition;
  11. },
  12. });

9、路由懒加载

当打包构建应用时,JavaScript 包会变得非常大,影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了。

举个例子:

  1. const Foo = () => import(/* webpackChunkName: "foo" */ './Foo.vue');
  2.  
  3. const router = new VueRouter({
  4. routes: [{ path: '/foo', component: Foo }],
  5. });

到此这篇关于Vue.js 前端路由和异步组件介绍的文章就介绍到这了,更多相关Vue.js 异步组件内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号