手写简易VueRouter

107 阅读4分钟

VueRouter本质

根据"不同的hash值"或者"不同的路径地址", 将不同的内容渲染到router-view中 所以实现VueRouter的核心关键点就在于如何监听'hash'或'路径'的变化, 再将不同的内容写到router-view

popstate监听历史记录点

vue-router 的 history 模式是使用浏览器的 history state 来实现的,history state 是通过 History 对象来操作的。 popstate 事件是通过 window.addEventListener('popstate') 进行注册的。但触发条件需要满足下面两点:

  1. 点击浏览器的【前进】【后退】按钮,或者调用 history 对象的 backforwardgo 方法
  2. 之前调用过 history 对象的 replaceState 或 pushState 方法
<a onclick="go('/home')">首页</a>
<a onclick="go('/about')">关于</a>
<div id="html"></div>
function go(path) {
    // console.log(path);
    history.pushState(null, null, path);
    document.querySelector('#html').innerHTML = path;
}
window.addEventListener('popstate', ()=>{
    console.log('点击了前进或者后退', location.pathname);
    document.querySelector('#html').innerHTML = location.pathname;
})

hashchange 事件

  • 当URL的片段标识符更改时,将触发hashchange事件(跟在#符号后面的URL部分,包括#符号)
  • hashchange事件触发时,事件对象会有hash改变前的URL(oldURL)hash改变后的URL(newURL)两个属性
window.addEventListener('hashchange', ()=>{
    // console.log('当前的hash值发生了变化');
    let currentHash = location.hash.slice(1);
    document.querySelector('#html').innerHTML = currentHash;
})

VueRouter结构

src-> router-> index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/home',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
]

const router = new VueRouter({
  mode: 'history', 
  base: process.env.BASE_URL,
  routes
})

export default router

提取路由信息

创建一个新的js文件(myVue-Router.js),搭建基本的路由信息框架

class VueRouter {
    constructor(options){
        this.mode = options.mode || 'hash';
        this.routes = options.routes || [];
        this.routesMap = this.createRoutesMap();
    }
    createRoutesMap(){
        return  this.routes.reduce((map, route)=>{
            map[route.path] = route.component;
            return map;
        }, {})
    }
}
VueRouter.install = (Vue, options)=>{

}
export default VueRouter;

初始化路由信息

class VueRouteInfo {
    constructor(){
        this.currentPath = null;
    }
}
class VueRouter {
    constructor(options){
        this.mode = options.mode || 'hash';
        this.routes = options.routes || [];
        // 提取路由信息
        this.routesMap = this.createRoutesMap();
        // 记录当前路由
        this.routeInfo = new VueRouteInfo();
        // 初始化默认的路由信息
        this.initDefault();
    }
    initDefault(){
        if(this.mode === 'hash'){
            // 1.判断打开的界面有没有hash, 如果没有就跳转到#/
            if(!location.hash){
                location.hash = '/';
            }
            // 2.加载完成之后和hash发生变化之后都需要保存当前的地址
            window.addEventListener('load', ()=>{
                this.routeInfo.currentPath = location.hash.slice(1);
            });
            window.addEventListener('hashchange', ()=>{
                this.routeInfo.currentPath = location.hash.slice(1);
                console.log(this.routeInfo);
            });
        }else{
            // 1.判断打开的界面有没有路径, 如果没有就跳转到/
            if(!location.pathname){
                location.pathname = '/';
            }
            // 2.加载完成之后和history发生变化之后都需要保存当前的地址
            window.addEventListener('load', ()=>{
                this.routeInfo.currentPath = location.pathname;
            });
            window.addEventListener('popstate', ()=>{
                this.routeInfo.currentPath = location.pathname;
                console.log(this.routeInfo);
            });
        }
    }
    createRoutesMap(){
        return  this.routes.reduce((map, route)=>{
            map[route.path] = route.component;
            // { /home: Home }
            return map;
        }, {})
    }
}
VueRouter.install = (Vue, options)=>{

}
export default VueRouter;

注入全局属性

VueRouter.install = (vm, options)=>{
    vm.mixin({
        beforeCreate(){
            if(this.$options && this.$options.router){
                this.$router = this.$options.router;
                this.$route = this.$router.routeInfo;
                // 实时监听路由变化
                vm.util.defineReactive(this, 'xxx', this.$router);
            }else{
                this.$router = this.$parent.$router;
                this.$route = this.$router.routeInfo;
            }
        }
    });
}

自定义RouterLink

vm.component('router-link', {
    props: {
        to: String
    },
    render(){
        // console.log(this._self.$router.mode);
        let path = this.to;
        if(this._self.$router.mode === 'hash'){
            path = '#' + path;
        }
        return <a href={path}>{this.$slots.default}</a>
    }
});

#自定义RouterView

vm.component('router-view', {
    render(h){
        let routesMap = this._self.$router.routesMap;
        let currentPath = this._self.$route.currentPath;
        let currentComponent = routesMap[currentPath];
        return h(currentComponent);
    }
});

完整示例一

App.vue

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/home">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <router-view></router-view>
  </div>
</template>

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

src-> router-> index.js 看上面的VueRouter结构

src-> router-> myVue-Router.js

class VueRouteInfo {
  constructor(){
    this.currentPath = null;
  }
}
class VueRouter{
  constructor(options){
    this.mode = options.mode || 'hash';
    this.routes = options.routes || [];
    // 1、提取路由信息
    this.routesMap = this.createRoutesMap();
    this.routeInfo = new VueRouteInfo();
    // 2、初始化默认的路由信息
    this.initDefault();
  }
  createRoutesMap(){
    return this.routes.reduce((map, route) =>{
      // 组件作为key返回
      map[route.path] = route.component;
      return map;
    },{})
  }
  initDefault(){
    if (this.mode === 'hash'){
      // 1) 判断打开的界面有没有hash, 如果没有就跳转到#/
      if (!location.hash){
        location.hash = '/'
      }
      // 2) 加载完成之后和hash发生变化之后都需要保存当前的地址
      window.addEventListener('load', ()=>{
        this.routeInfo.currentPath = location.hash.slice(1);
      });
      window.addEventListener('hashchange', ()=>{
        this.routeInfo.currentPath = location.hash.slice(1)
      })
    } else {
      // 1) 判断打开的界面有没有路径, 如果没有就跳转到/
      if (!location.pathname){
        location.pathname = '/'
      }
      // 2)加载完成之后和history发生变化之后都需要保存当前的地址
      window.addEventListener('load', ()=>{
        this.routeInfo.currentPath = location.pathname
      });
      window.addEventListener('popstate', ()=>{
        this.routeInfo.currentPath = location.pathname;
      });
    }
  }
}
VueRouter.install = (vm, options) =>{
  // 3、全局注入属性
  vm.mixin({
    beforeCreate() {
      if (this.$options && this.$options.router){
        this.$router = this.$options.router;
        this.$route = this.$router.routeInfo;
        // 实时监听路由变化
        vm.util.defineReactive(this, 'xxx', this.$router);
      } else {
        this.$router = this.$parent.$router;
        this.$route = this.$router.routeInfo;
      }

    }
  });
  // 4、自定义路由组件
  vm.component('router-link', {
    props: {
      to: String
    },
    render() {
      let path = this.to;
      if(this._self.$router.mode === 'hash'){
        path = '#' + path;
      }
      return<a href={path}>{this.$slots.default}</a>
    }
  })
  vm.component('router-view', {
    render(h) {
      let routerMap = this._self.$router.routesMap;
      let currentPath = this._self.$route.currentPath;
      let currentComponent = routerMap[currentPath];
      return h(currentComponent)

    }
  })
};
export default VueRouter

嵌套路由

嵌套路由需要记录子路由同时也需要保存父路由,这时候修改一个class的结构,添加一个matched数组,保存对应路由

constructor(options){
  Vue.util.defineReactive(this, "matched", []);
  this.createRoutesMap();
}

// 修改路由接收方式
createRoutesMap(routes){
  routes = routes || this.routes
  for (const route of routes) {
    if (route.path === "/" && this.routeInfo.currentPath === "/") {
      this.matched.push(route);
      return;
    }
    if (route.path !== "/" && this.routeInfo.currentPath && this.routeInfo.currentPath.includes(route.path)) {
      this.matched.push(route);
      if (route.children) {
        this.createRoutesMap(route.children);
      }
      return;
    }
  }
}
// 路由跳转时,初始化matched
initDefault(){
  const hashLoad =() =>{
    this.routeInfo.currentPath = location.hash.slice(1);
    this.matched = [];
    this.createRoutesMap();
  }
  const historyLoad =() =>{
    this.routeInfo.currentPath = location.pathname
    this.matched = [];
    this.createRoutesMap();
  }
  if (this.mode === 'hash'){
    // 1) 判断打开的界面有没有hash, 如果没有就跳转到#/
    if (!location.hash){
      location.hash = '/'
    }
    // 2) 加载完成之后和hash发生变化之后都需要保存当前的地址
    window.addEventListener('load', ()=>{
      hashLoad()
    });
    window.addEventListener('hashchange', ()=>{
      hashLoad()
    })
  } else {
    // 1) 判断打开的界面有没有路径, 如果没有就跳转到/
    if (!location.pathname){
      location.pathname = '/'
    }
    // 2)加载完成之后和history发生变化之后都需要保存当前的地址
    window.addEventListener('load', ()=>{
      historyLoad()
    });
    window.addEventListener('popstate', ()=>{
      historyLoad()
    });
  }
}

修改router-view 参考链接 www.codenong.com/cs105176997…

Vue.component('router-view', {
  render(h) {
    // this.$vnode是当前组件的虚拟dom,我们在它虚拟dom的data属性中设置一个自定义的属性,
    // 代表自己是一个routerview
    // 需要标记当前路由的深度,循环获取父组件,如果父组件的routerview为true,则代表自己的深度加1
    this.$vnode.data.routerView = true; 
    let depth = 0;
    let parent = this.$parent;
    while (parent) {
      const vnodeData = parent.$vnode && parent.$vnode.data;
      if (vnodeData && vnodeData.routerView) {
        depth++;
      }
      parent = parent.$parent;
    }
    const currentRoute = this.$router.matched[depth]
    const currentComponent = currentRoute && currentRoute.component || null
    return h(currentComponent);
  }
})

修改结构

const routes = [
  {
    path: '/home',
    name: 'Home',
    component: Home,
    children:[
      {
        path: '/homeInfo',
        name: 'HomeInfo',
        component: HomeInfo,
      },
      {
        path: '/homeData',
        name: 'HomeData',
        component: HomeData,
      },
    ]
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
]

在Home组件添加嵌套路由

<template>
  <div class="home">
    <div>
      <h1>我是Home</h1>
      <router-link to="/home/homeInfo">homeInfo</router-link>
    </div>
              <router-view></router-view>
  </div>
</template>

完整示例二

let Vue;
function cleanPath (path) {
  return path.replace(////g, '/')
}
class VueRouteInfo {
  constructor() {
    this.currentPath = null;
  }
}
class VueRouter{
  constructor(options){
    this.mode = options.mode || 'hash';
    // 1、提取路由信息
    this.routes = options.routes || [];
    this.routeInfo = new VueRouteInfo();
    // 2、初始化默认的路由信息
    this.initDefault();
    Vue.util.defineReactive(this, "matched", []);
    this.createRoutesMap();
  }
  createRoutesMap(routes){
    routes = routes || this.routes
    for (const route of routes) {
      if (route.path === "/" && this.routeInfo.currentPath === "/") {
        this.matched.push(route);
        return;
      }
      if (route.path !== "/" && this.routeInfo.currentPath && this.routeInfo.currentPath.includes(route.path)) {
        this.matched.push(route);
        if (route.children) {
          this.createRoutesMap(route.children);
        }
        return;
      }
    }
  }
  initDefault(){
    const hashLoad =() =>{
      this.routeInfo.currentPath = location.hash.slice(1);
      this.matched = [];
      this.createRoutesMap();
    }
    const historyLoad =() =>{
      this.routeInfo.currentPath = location.pathname
      this.matched = [];
      this.createRoutesMap();
    }
    if (this.mode === 'hash'){
      // 1) 判断打开的界面有没有hash, 如果没有就跳转到#/
      if (!location.hash){
        location.hash = '/'
      }
      // 2) 加载完成之后和hash发生变化之后都需要保存当前的地址
      window.addEventListener('load', ()=>{
        hashLoad()
      });
      window.addEventListener('hashchange', ()=>{
        hashLoad()
      })
    } else {
      // 1) 判断打开的界面有没有路径, 如果没有就跳转到/
      if (!location.pathname){
        location.pathname = '/'
      }
      // 2)加载完成之后和history发生变化之后都需要保存当前的地址
      window.addEventListener('load', ()=>{
        historyLoad()
      });
      window.addEventListener('popstate', ()=>{
        historyLoad()
      });
    }
  }
  addRouteRecord(route,path){
    let routeModule = route
    if (routeModule.children){
      routeModule.children.map((child) =>{
        let childMatchAs = path ? cleanPath((path + "/" + (child.path))) : undefined;
        child.path = childMatchAs
        this.addRouteRecord(child,childMatchAs)
        return child
      })
    }
    return routeModule
  }

}
VueRouter.install = (vm, options) =>{
  // 3、全局注入属性
  Vue = vm
  Vue.mixin({
    beforeCreate() {
      if (this.$options && this.$options.router){
        this.$router = this.$options.router;
        this.$route = this.$router.routeInfo;
        // 实时监听路由变化
        Vue.util.defineReactive(this, 'xxx', this.$router);
      } else {
        this.$router = this.$parent.$router;
        this.$route = this.$router.routeInfo;
      }

    }
  });
  // 4、自定义路由组件
  Vue.component('router-link', {
    props: {
      to: String
    },
    render() {
      let path = this.to;
      if(this._self.$router.mode === 'hash'){
        path = '#' + path;
      }
      return<a href={path}>{this.$slots.default}</a>
    }
  })
  Vue.component('router-view', {
    render(h) {
      // this.$vnode是当前组件的虚拟dom,我们在它虚拟dom的data属性中设置一个自定义的属性,代表自己是一个routerview
      // 需要标记当前路由的深度,循环获取父组件,如果父组件的routerview为true,则代表自己的深度加1
      this.$vnode.data.routerView = true;
      let depth = 0;
      let parent = this.$parent;
      while (parent) {
        const vnodeData = parent.$vnode && parent.$vnode.data;
        if (vnodeData && vnodeData.routerView) {
          depth++;
        }
        parent = parent.$parent;
      }
      const currentRoute = this.$router.matched[depth]
      const currentComponent = currentRoute && currentRoute.component || null
      return h(currentComponent);
    }
  })
};

export default VueRouter