首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【今天学了什么】前端路由的实现原理

【今天学了什么】前端路由的实现原理

作者头像
Daotin
发布2022-05-09 20:53:58
6940
发布2022-05-09 20:53:58
举报

什么是前端路由?

路由的概念来源于服务端,在服务端中路由描述的是 URL 与处理函数之间的映射关系。

在 Web 前端单页应用 SPA(Single Page Application)中,路由描述的是 URL 与 UI 之间的映射关系,这种映射是单向的,即 URL 变化引起 UI 更新(无需刷新页面)。

如何实现前端路由?

要实现前端路由,需要解决两个核心:

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

下面分别使用 hash 和 history 两种实现方式回答上面的两个核心问题。

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 变化。

原生JS实现

hash 方式

<body>
  <ul>
    <!-- 定义路由 -->
    <li><a href="#/home">home</a></li>
    <li><a href="#/about">about</a></li>

    <!-- 渲染路由对应的 UI -->
    <div id="routeView"></div>
  </ul>
</body>

<script>
	// 页面加载完不会触发 hashchange,这里主动触发一次 hashchange 事件
	window.addEventListener('DOMContentLoaded', onLoad)
	// 监听路由变化
	window.addEventListener('hashchange', onHashChange)
	
	// 路由视图
	var routerView = null
	
	function onLoad () {
	  routerView = document.querySelector('#routeView')
	  onHashChange()
	}
	
	// 路由变化时,根据路由渲染对应 UI
	function onHashChange () {
	  switch (location.hash) {
	    case '#/home':
	      routerView.innerHTML = 'Home'
	      return
	    case '#/about':
	      routerView.innerHTML = 'About'
	      return
	    default:
	      return
	  }
	}
</script>

history方式

<script>
	// 页面加载完不会触发 hashchange,这里主动触发一次 hashchange 事件
	window.addEventListener('DOMContentLoaded', onLoad);
	// 监听路由变化
	window.addEventListener('popstate', onPopState);
	
	// 路由视图
	var routerView = null;
	
	function onLoad() {
	    routerView = document.querySelector('.vanilla.history .container');
	    onPopState();
	
	    // 拦截 <a> 标签点击事件默认行为, 点击时使用 pushState 修改 URL并更新手动 UI,从而实现点击链接更新 URL 和 UI 的效果。
	    var linkList = document.querySelectorAll('.vanilla.history 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 = '<h2>Home</h2>';
	            return;
	        case '/about':
	            routerView.innerHTML = '<h2>About</h2>';
	            return;
	        default:
	            return;
	    }
	}
</script>

vue实现router-link和router-view

在vue里面我们一般实现路由采用的是vue-router插件实现的,这里我们不采用vue-router插件,而是自己实现类似的路由功能。

需要注意的是,vue-router增加了很多特性,如动态路由、路由参数、路由动画等等,这些导致路由实现变的复杂。所以这里只是对前端路由最核心部分的实现。

hash方式

html文件

<div class="vue hash">
    <h1>Hash Router(Vue)</h1>
    <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>

index.js文件

import Vue from 'vue/dist/vue.esm.browser'
import RouterView from './RouterView.vue'
import RouterLink from './RouterLink.vue'

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-link.vue文件

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

<script>
export default {
  props: {
    to: String
  },
  methods: {
    onClick () {
      window.location.hash = '#' + this.to
    }
  }
}
</script>

router-view.vue 文件

<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,this.$root,this.routeView );
        }
    }
};
</script>

history方式

html文件

<div class="vue history">
   <h1>History Router(Vue)</h1>
    <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>

index.js文件

import Vue from 'vue/dist/vue.esm.browser'
import RouterView from './RouterView.vue'
import RouterLink from './RouterLink.vue'

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-link.vue文件

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

router-view.vue文件

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

参考连接:

  • https://mp.weixin.qq.com/s/XV7tGdB6bDbZT4h5H8Y3yw
  • https://github.com/whinc/web-router-principle
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 什么是前端路由?
  • 如何实现前端路由?
  • 原生JS实现
    • hash 方式
      • history方式
      • vue实现router-link和router-view
        • hash方式
          • history方式
          • 参考连接:
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档