I
M
A
G
I
N
E

前端路由的实现

路由概念

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

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

前端路由的实现

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

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

hash实现

history实现

hash和history API对比

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

原生实现前端路由

  • hash:
    images
    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>

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
    }
  }
  • history
    images
    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>

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

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>
posted @ 2021-01-20 15:35  Imagine、  阅读(109)  评论(0编辑  收藏  举报