IMAGINE'S BLOG IMAGINE'S BLOG
首页
  • 原生JS

    • JavaScript
  • 前端框架扩展

    • Vue
    • React
    • UI组件库
  • HTML
  • CSS
  • 浏览器
  • 分类
  • 标签
  • 归档
  • 技术文档
  • GitHub相关
  • Nodejs
关于
  • 网站
  • 友情链接
GitHub (opens new window)

peng

平平无奇的web前端开发一枚
首页
  • 原生JS

    • JavaScript
  • 前端框架扩展

    • Vue
    • React
    • UI组件库
  • HTML
  • CSS
  • 浏览器
  • 分类
  • 标签
  • 归档
  • 技术文档
  • GitHub相关
  • Nodejs
关于
  • 网站
  • 友情链接
GitHub (opens new window)
  • JavaScript

    • javascript 之 this 指向问题
    • JS循环遍历方法
    • 前端常用公共方法工具类
    • JS声明提升
    • JS合并数组对象中key值相同的数据
    • 数组对象求和
    • 前端路由实现
      • 路由概念
      • 前端路由的实现
      • 原生实现前端路由
      • React-Router 实现
      • Vue-Router 实现
    • Promise(一):Promise 认识
    • Promise(二):手动实现一个 Promise
    • Promise(三):拓展方法实现
    • JS forEach踩坑
    • ES6-ES12 特性
    • async/await
    • JavaScript 数组去重
    • js对象排序
    • js if/else 语句优化策略
    • js深拷贝
    • 正则表达式校验
    • js笛卡尔积
    • Axios 封装
  • 框架扩展

  • 前端乱炖
  • JavaScript
peng
2022-09-05
目录

前端路由实现

# 路由概念

路由的本质其实就是一种对应关系,比如说我们在浏览器地址栏输入 URL 地址后,浏览器就会请求对应的 URL 地址的资源;URL 地址和真实的资源之间就会形成一种对应的关系,就是路由。 路由主要分为前端路由和后端路由。 后端路由又称为服务端路由,服务端中路由描述的是 URL 与处理函数之间的映射关系

前端路由主要应用于 SPA 单页面应用架构,SPA 页面只有一个主页面,也就是挂载点,所有的页面内容都依赖于挂载点上,通过动态替换 DOM 内容和同步去修改 URL 地址来实现多页面的效果; 前端路由描述的是 URL 和 UI 之间的映射关系,这种映射是单向的,通过 URL 的改变引起 UI 的更新,而且无需刷新页面。

#

# 前端路由的实现

要实现前端路由,必须解决两个核心问题:

  • 如何改变 URL 却不引起页面刷新?
  • 如何检测 URL 的变化?

hash 实现

  • hash 是 URL 中 hash(#)及后面的那部分,常用作锚点在页面内进行导航,改变 URL 中的 hash 部分不会引起页面刷新
  • 通过 hashchange 事件监听 URL 的变化,改变 URL 的方式只有这几种:通过浏览器前进后退改变 URL、通过 a 标签改变 URL、通过 window.location 改变 URL,这几种情况改变 URL 都会触发 hashchange 事件

history 实现

  • history 提供了pushState 和 replaceState两个方法,这两个方法改变 URL 的 path 部分不会引起页面刷新
  • history 提供类似 hashchange 事件的 popstate 事件,但 popstate 事件有些不同:通过浏览器前进后退改变 URL 时会触发 popstate 事件,通过 pushState/replaceState 或 a 标签改变 URL 不会触发 popstate 事件。好在我们可以拦截 pushState/replaceState 的调用和 a 标签的点击事件来检测 URL 变化,所以监听 URL 变化可以实现,只是没有 hashchange 那么方便

hash 和 history API 对比

对比项 hash history
url 不美观(#) 正常
命名限制 通常只能在同一个 document 下进行改变 url 地址可以自己来定义,只要是同一个域名下都可以,自由度更大
url 地址变更 会改变 可以改变,也可以不变
状态保存 无内置方法,需要另行保存页面的状态信息 将页面信息压入历史栈时可以附带自定义的信息
参数传递能力 受到 url 总长度的限制 将页面信息压入历史栈时可以附带自定义的信息
实用性 可直接使用 通常服务端需要修改代码以配合实现
兼容性 IE8 以上 IE10 以上

# 原生实现前端路由

  • hash:

    html:

<html>
  <body>
    <!--路由-->
    <ul>
      <li><a href="#/home">Home</a></li>
      <li><a href="#/about">About</a></li>
    </ul>

    <!--路由跳转渲染的view-->
    <div id="view"></div>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12

javascript:

// 当初始的 HTML 文档被完全加载和解析完成之后,DOMContentLoaded 事件被触发,而无需等待样式表、图像和子框架的完成加载
// 主动触发一次hashchange事件
window.addEventListener("DOMContentLoaded", onLoad);

// 监听路由变化
window.addEventListener("hashchange", onHashChange);

// 路由view
var routerView = null;

function onLoad() {
  routerView = document.querySelector("#view");
  onHashChange();
}

// 根据路由的变化,渲染对应的UI
function onHashChange() {
  switch (location.hash) {
    case "#/home":
      routerView.innerHTML = "Home";
      return;
    case "#/about":
      routerView.innerHTML = "About";
      return;
    default:
      return;
  }
}
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
  • history

    html:

<html>
  <body>
    <h3>History Router</h3>
    <!--路由-->
    <ul>
      <li><a href="/home">Home</a></li>
      <li><a href="/about">About</a></li>
    </ul>

    <!--路由跳转渲染的view-->
    <div id="view"></div>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13

javascript

// 当初始的 HTML 文档被完全加载和解析完成之后,DOMContentLoaded 事件被触发,而无需等待样式表、图像和子框架的完成加载
// 主动触发一次hashchange事件
window.addEventListener("DOMContentLoaded", onLoad);

// 监听路由变化
window.addEventListener("popstate", onPopState);

// 路由view
var routerView = null;

function onLoad() {
  routerView = document.querySelector("#view");
  onPopState();

  // 拦截a标签的点击事件默认行为,点击时使用pushState修改URL并手动更新UI
  var linkList = document.querySelectorAll("a[href]");
  linkList.forEach((el) =>
    el.addEventListener("click", function (e) {
      e.preventDefault();
      history.pushState(null, "", el.getAttribute("href"));
      onPopState();
    })
  );
}

// 根据路由的变化,渲染对应的UI
function onPopState() {
  switch (location.pathname) {
    case "/home":
      routerView.innerHTML = "Home";
      return;
    case "/about":
      routerView.innerHTML = "About";
      return;
    default:
      return;
  }
}
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

# React-Router 实现

  • hash
<BrowserRouter>
    <ul>
      <li>
        <Link to="/home">home</Link>
      </li>
      <li>
        <Link to="/about">about</Link>
      </li>
    </ul>

    <Route path="/home" render={() => <h2>Home</h2>} />
    <Route path="/about" render={() => <h2>About</h2>} />
  </BrowserRouter>
1
2
3
4
5
6
7
8
9
10
11
12
13

BrowserRouter 代码

export default class BrowserRouter extends React.Component {
  state = {
    currentPath: utils.extractHashPath(window.location.href),
  };

  onHashChange = (e) => {
    const currentPath = utils.extractHashPath(e.newURL);
    console.log("onHashChange:", currentPath);
    this.setState({ currentPath });
  };

  componentDidMount() {
    window.addEventListener("hashchange", this.onHashChange);
  }

  componentWillUnmount() {
    window.removeEventListener("hashchange", this.onHashChange);
  }

  render() {
    return (
      <RouteContext.Provider value={{ currentPath: this.state.currentPath }}>
        {this.props.children}
      </RouteContext.Provider>
    );
  }
}
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

Route 代码

export default ({ path, render }) => (
  <RouteContext.Consumer>
    {({ currentPath }) => currentPath === path && render()}
  </RouteContext.Consumer>
);
1
2
3
4
5

Link 代码

export default ({ to, ...props }) => <a {...props} href={"#" + to} />;
1
  • history
<HistoryRouter>
    <ul>
      <li>
        <Link to="/home">home</Link>
      </li>
      <li>
        <Link to="/about">about</Link>
      </li>
    </ul>

    <Route path="/home" render={() => <h2>Home</h2>} />
    <Route path="/about" render={() => <h2>About</h2>} />
  </HistoryRouter>
1
2
3
4
5
6
7
8
9
10
11
12
13

HistoryRouter 代码

export default class HistoryRouter extends React.Component {
  state = {
    currentPath: utils.extractUrlPath(window.location.href),
  };

  onPopState = (e) => {
    const currentPath = utils.extractUrlPath(window.location.href);
    console.log("onPopState:", currentPath);
    this.setState({ currentPath });
  };

  componentDidMount() {
    window.addEventListener("popstate", this.onPopState);
  }

  componentWillUnmount() {
    window.removeEventListener("popstate", this.onPopState);
  }

  render() {
    return (
      <RouteContext.Provider
        value={{
          currentPath: this.state.currentPath,
          onPopState: this.onPopState,
        }}
      >
        {this.props.children}
      </RouteContext.Provider>
    );
  }
}
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

Route 代码

export default ({ path, render }) => (
  <RouteContext.Consumer>
    {({ currentPath }) => currentPath === path && render()}
  </RouteContext.Consumer>
);
1
2
3
4
5

Link 代码

export default ({ to, ...props }) => (
  <RouteContext.Consumer>
    {({ onPopState }) => (
      <a
        href=""
        {...props}
        onClick={(e) => {
          e.preventDefault();
          window.history.pushState(null, "", to);
          onPopState();
        }}
      />
    )}
  </RouteContext.Consumer>
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# Vue-Router 实现

  • hash
<div>
  <ul>
    <li><router-link to="/home">home</router-link></li>
    <li><router-link to="/about">about</router-link></li>
  </ul>
  <router-view></router-view>
</div>
1
2
3
4
5
6
7
const routes = {
  "/home": {
    template: "<h2>Home</h2>",
  },
  "/about": {
    template: "<h2>About</h2>",
  },
};

const app = new Vue({
  el: ".vue.hash",
  components: {
    "router-view": RouterView,
    "router-link": RouterLink,
  },
  beforeCreate() {
    this.$routes = routes;
  },
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

router-view 代码

<template>
  <component :is="routeView" />
</template>

<script>
import utils from '~/utils.js'
export default {
  data () {
    return {
      routeView: null
    }
  },
  created () {
    this.boundHashChange = this.onHashChange.bind(this)
  },
  beforeMount () {
    window.addEventListener('hashchange', this.boundHashChange)
  },
  mounted () {
    this.onHashChange()
  },
  beforeDestroy() {
    window.removeEventListener('hashchange', this.boundHashChange)
  },
  methods: {
    onHashChange () {
      const path = utils.extractHashPath(window.location.href)
      this.routeView = this.$root.$routes[path] || null
      console.log('vue:hashchange:', path)
    }
  }
}
</script>
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

router-link 代码

<template>
  <a @click.prevent="onClick" href=''><slot></slot></a>
</template>

<script>
export default {
  props: {
    to: String
  },
  methods: {
    onClick () {
      window.location.hash = '#' + this.to
    }
  }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  • history
<div>
  <ul>
    <li><router-link to="/home">home</router-link></li>
    <li><router-link to="/about">about</router-link></li>
  </ul>
  <router-view></router-view>
</div>
1
2
3
4
5
6
7
const routes = {
  "/home": {
    template: "<h2>Home</h2>",
  },
  "/about": {
    template: "<h2>About</h2>",
  },
};

const app = new Vue({
  el: ".vue.history",
  components: {
    "router-view": RouterView,
    "router-link": RouterLink,
  },
  created() {
    this.$routes = routes;
    this.boundPopState = this.onPopState.bind(this);
  },
  beforeMount() {
    window.addEventListener("popstate", this.boundPopState);
  },
  beforeDestroy() {
    window.removeEventListener("popstate", this.boundPopState);
  },
  methods: {
    onPopState(...args) {
      this.$emit("popstate", ...args);
    },
  },
});
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

router-view 代码

<template>
  <component :is="routeView" />
</template>

<script>
import utils from '~/utils.js'
export default {
  data () {
    return {
      routeView: null
    }
  },
  created () {
    this.boundPopState = this.onPopState.bind(this)
  },
  beforeMount () {
    this.$root.$on('popstate', this.boundPopState)
  },
  beforeDestroy() {
    this.$root.$off('popstate', this.boundPopState)
  },
  methods: {
    onPopState (e) {
      const path = utils.extractUrlPath(window.location.href)
      this.routeView = this.$root.$routes[path] || null
      console.log('[Vue] popstate:', path)
    }
  }
}
</script>
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

router-link 代码

<template>
  <a @click.prevent="onClick" href=''><slot></slot></a>
</template>

<script>
export default {
  props: {
    to: String
  },

  methods: {
    onClick () {
      history.pushState(null, '', this.to)
      this.$root.$emit('popstate')
    }
  }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#Router
上次更新: 2022/09/06, 10:30:04
数组对象求和
Promise(一):Promise 认识

← 数组对象求和 Promise(一):Promise 认识→

最近更新
01
Axios 封装
09-06
02
MySQL数据库常用操作
09-06
03
解决element表格数据量过大导致页面渲染缓慢、卡顿问题
09-06
更多文章>
Theme by Vdoing | Copyright © 2020-2024 peng | IMAGINE
image | imgloc.com
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式