Skip to content
一、路由拦截

路由拦截:顾名思义通过监听路由的变化,来达到预期的目地。

  • main/micro/start.js 中,导入 rewriteRouter方法,并且调用执行。

    javascript
    import { rewriteRouter } from './router/rewriteRouter'
    
    // 实现路由拦截
    rewriteRouter()
  • main/micro/router/rewriteRouter.js 暴露 rewriteRouter

    javascript
    import { patchRouter } from '../utils/index'
    
    /**
      * 重写 window 的路由跳转
      */
      export const rewriteRouter = () => {
        window.history.pushState = patchRouter(window.history.pushState, 'micro_push')
        window.history.replaceState = patchRouter(window.history.replaceState, 'micro_replace')
    }
  • main/micro/utils/index.js 中封装 patchRouter

    javascript
    /**
      * 给当前的路由跳转打补丁
      * @param globalEvent
      * @param eventName
      * @return {(function(): void)|*}
      */
      export const patchRouter = (globalEvent, eventName) => {
          return  function () {
              // 创建一个新的事件
              const e = new Event(eventName)
              // 传入的原生事件来代替 整个 function 的执行
              globalEvent.apply(this, arguments)
              // 触发创建的好的新的事件
              window.dispatchEvent(e)
          }
      }
  • main/micro/router/rewriteRouter.jsrewriteRouter 添加监听事件

    javascript
    import { turnApp } from '../router/routerHandle'
    /**
     * 重写 window 的路由跳转
     */
    export const rewriteRouter = () => {
        ...        
        // 添加事件的监听
        window.addEventListener('micro_push', turnApp)
        window.addEventListener('micro_replace', turnApp)
    }
  • main/micro/router/routerHandle.js 暴露 routerHandle 自定义路由事件回调

    javascript
    export const turnApp = () => {
      console.log('路由切换了')
    }
  • main/micro/router/rewriteRouter.jsrewriteRouter 添加浏览器返回监听

    javascript
    export const rewriteRouter = () => {
      ...
      // 点击返回,也需要拦截
      window.onpopstate = function () {
        turnApp()
      }
    }
  • 最终实现的效果 micro-main-router-listen.png

Released under the MIT License.