zoukankan      html  css  js  c++  java
  • 前端路由的实现原理

    什么是前端路由?

    路由的概念来源于服务端,在服务端中路由描述的是 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 提供了 pushStatereplaceState 两个方法,这两个方法改变 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>
    
    
    

    参考连接:

  • 相关阅读:
    欢迎大家来到氨帝萝卜的博客园
    Java利用自定义注解、反射实现简单BaseDao
    spring boot 2.0.1.RELEASE版本之消息总线 ConfigClient配置自动刷新
    spring cloud eureka server之端口8889之谜
    关于spring cloud “Finchley.RC2”版本在spring cloud config中的ArrayIndexOutOfBoundsException
    关于中间件、J2EE的一些概念
    IP地址 子网掩码 默认网关 DNS(转)
    知识点大图
    Javascript是单线程的深入分析(转)
    SQL查询--选择运算(1)
  • 原文地址:https://www.cnblogs.com/lvonve/p/11250147.html
Copyright © 2011-2022 走看看