前端路由的实现原理

什么是前端路由?

路由的概念来源于服务端,在服务端中路由描述的是 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>

参考连接:

  • https://mp.weixin.qq.com/s/XV7tGdB6bDbZT4h5H8Y3yw
  • https://github.com/whinc/web-router-principle

转载于:https://www.cnblogs.com/lvonve/p/11250147.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值