Skip to content
On this page

介绍

实现单页面开发的方式

  • 通过 hash 记录跳转的路径(可以产生历史管理)
  • 浏览器自带的历史管理的方法的 history(history.pushState()) 可能导致 404 错误

开发时使用 hash 的方式上线的话我们会使用 history 的方式

路由

单页面 web 应用 (singie page web application,SPA), 就是只有一张 web 页面的应用,是加载 html 页面并在用户与应用程序交互动态更新该页面的 web 应用程序

vue-router 介绍

可以配置组件和路由映射,可以使用 Vue.js + vue-router 创建单页引用

vue-router

  • npm 方式

npm install vue-router --save

  • 直接应用方式

https://unpkg.com/vue-router@2.0.0/dist/vue-router.js

路由

访问不同的路径,就可以返回不同的结果

多页面 (spa)

single page application

前后端分离

后端只负责接口供前端调用,像跳转都是前端自己处理的 hash 模式 hash 模式 # 开发时使用 hash 不会导致 404  但是不支持 seo h5 的 history.pushState

前端路由的实现原理

前端路由的实现原理:两种模式 一种 hash 模式,一种 history 模式 h5api

javascript
window.location.hash = '/'
history.pushState(state,null)
history.replaceState()
1
2
3

history

目前浏览器都支持 history.pushState

javascript
history.pushState({ a: 1 }, null, "/about");
history.pushState({ a: 1 }, null, "#/about");
1
2

两种路由的区别

hash

hash 模式的好处 就是锚点,刷新页面的时候,不会想服务器发送请求,同时他不支持服务端渲染(不能做 seo 优化) 不会参数 404

history

特点就是路径漂亮 没有# 和正常页面切换一样,如果刷新页面会像服务器发送请求,如果资源不存在会出现 404

html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 创建状态管理
      function buildSate(
        back, //后退
        current, //当前
        forward, //向前
        replace = false, // replace还是push
        computedScroll = false
      ) {
        return {
          back,
          current,
          forward,
          replace,
          scroll: computedScroll
            ? { left: window.pageXOffset, top: window.pageYOffset }
            : null,
          postition: window.history.length,
        };
      }

      // 创建当前页面位置
      function createCurrentLocation() {
        const { pathname, search, hash } = window.location;
        return pathname + search + hash;
      }

      function useHistoryStateNavigation() {
        const currentLocation = {
          value: createCurrentLocation(),
        };
        const historyState = {
          value: window.history.state,
        };
        // 第一次刷新页面 此时没有任何状态,那么我就自己维护一个状态(页面后退是哪一个路径,当前路径是哪个,要去哪里,我是用的push跳转,replace跳转、跳转后滚动条位置是哪)
        if (!historyState.value) {
          console.log(buildSate(null, currentLocation.value, null, true));
        }
        console.log(currentLocation, historyState);
      }

      function createWebHistory() {
        //   1.路由系统最基本的得包含当前的路径,当前路径下他的状态是什么,需要提供两个切换路径的方法push replace
        const historyNavigation = useHistoryStateNavigation();
      }

      const history = createWebHistory();
      // 实现路由监听,如果路径变化需要通知用户
    </script>
  </body>
</html>

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
沪ICP备20006251号-1