前端路由实现

198 阅读4分钟

路由概念

路由的本质其实就是一种对应关系,比如说我们在浏览器地址栏输入 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 对比

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

原生实现前端路由

hash:

image.png

<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>
// 当初始的 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;
  }
}

history:

image.png

<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>
// 当初始的 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;
  }
}

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>

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>
    );
  }
}

Route 代码

export default ({ path, render }) => (
  <RouteContext.Consumer>
    {({ currentPath }) => currentPath === path && render()}
  </RouteContext.Consumer>
);

Link 代码

export default ({ to, ...props }) => <a {...props} href={"#" + to} />;
  • 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>

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>
    );
  }
}

Route 代码

export default ({ path, render }) => (
  <RouteContext.Consumer>
    {({ currentPath }) => currentPath === path && render()}
  </RouteContext.Consumer>
);

Link 代码

export default ({ to, ...props }) => (
  <RouteContext.Consumer>
    {({ onPopState }) => (
      <a
        href=""
        {...props}
        onClick={(e) => {
          e.preventDefault();
          window.history.pushState(null, "", to);
          onPopState();
        }}
      />
    )}
  </RouteContext.Consumer>
);

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>
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;
  },
});

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>

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>
  • 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>
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);
    },
  },
});

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>

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>