手写简易VueRouter

前言

路由是用来跟后端服务器进行交互的一种方式,通过不同的路径来请求不同的资源,请求不同的页面是路由的其中一项功能。VueRouter则是Vue的路由管理器

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

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值