前端路由的實現原理


什么是前端路由?

路由的概念來源於服務端,在服務端中路由描述的是 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>


參考連接:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM