使用原生JS封装Vue-Router

摘要

前段时间对Vue-router里面的一些方法原理进行了实现,在这里进行整理一下,相比于上一篇实现的axios,这次实现的路由显得更复杂一些。
实现的方法主要有push,go,replace以及beforeEach和afterEach的钩子函数。
实现的原理主要有URL和页面的响应,以及router-view和router-link。

1.hash和history

在写之前我们要了解hash和history的区别,主要的区别还是在于

hash模式更改路由不需要重新请求,并且URL中路由前面有#。
history模式下,URL中路由前面没有#,并且更改URL会重新请求。

我们不管对于什么方法的实现都要兼容这两种模式。
而Vue-router在创建实例的时候也可以进行设置是hash模式还是history模式。
所以我们的类在创建的时候需要这么写:

function myrouter (obj) {
    
    
  this.mode = obj.mode || 'hash'
}

2.push,go,replace方法

首先我们还没有实现router-view,所以在页面中我们先使用一个h1标签来代替。

(1) push

对于hash模式,我们直接更改URL的hash值就可以。
但在history模式下,我们需要使用pushState这个方法。

myrouter.prototype.push = function (data) {
    
    
  //判断路由模式
  if (this.mode == 'hash') {
    
    
    location.href = orgin + '/#' + ifObj(data);
    h1.innerHTML = ifObj(data)
  }
  else if (this.mode = 'history') {
    
    
    history.pushState({
    
    }, '', orgin + ifObj(data))
    h1.innerHTML = ifObj(data)
  }
}

ifObj是判断是否为对象的方法:

//判断参数类型
function ifObj (data) {
    
    
  if (typeof data == 'object') {
    
    
    return data.path
  } else {
    
    
    return data;
  }
}

(2) go

对于go方法,就显得更简单了,直接用就可:

myrouter.prototype.go = function (num) {
    
    
  history.go(num)
}

(3) replace

对于replace方法,我们在
hash模式下,需要调用location.replace()方法。
history模式下,需要调用replaceState()方法。

myrouter.prototype.replace = function (data) {
    
    
  let orgin = location.origin;
  //判断路由模式
  if (this.mode == 'hash') {
    
    
    //判断是否使用路由拦截
    location.replace(orgin + '/#' + ifObj(data));
    h1.innerHTML = ifObj(data)
  } else if (this.mode == 'history') {
    
    
    history.replaceState({
    
    }, '', orgin + ifObj(data))
    h1.innerHTML = ifObj(data)
  }
}

OK,对于这三个方法我们已经实现了最基本的功能,但是在后面还需要对其进行更改。包括路由拦截都会影响这三个方法。

3.监听方法

首先即便是我们实现了这三个方法,但是,如果我们直接在URL中更改路由,页面是依旧不会给响应的,所以我们要对页面的URL进行监听。

而window自带了一些监听URL的方法:
对于hash模式:onhashchange可以监听hash值的变化。
对于history模式:onpopstatea可以监听前进后退等的操作。

myrouter.prototype.update = function () {
    
    
  let _this = this;
  //判断路由模式
  if (this.mode == 'hash') {
    
    
    //监听url哈希值的变化
    window.onhashchange = function () {
    
    
      h1.innerHTML = location.hash.replace('#/', '')
    }
  }
  else if (this.mode == 'history') {
    
    
    //监听history模式下前进后退的操作
    window.addEventListener('popstate', function () {
    
    
      h1.innerHTML = location.pathname
    });
    window.onload = function () {
    
    
      h1.innerHTML = location.pathname
    }
  }
}

这里面,onload的作用主要是,在history模式下,我们更改页面的URL会刷新页面,所以我们采用onload方法来进行监听。

4.beforeEach钩子函数

我们知道,beforeEach钩子函数接受了一个回调函数作为参数,所以在我们的源码里面我们需要将这个回调函数保存下来:

myrouter.prototype.beforeEach = function (config) {
    
    
  this.saveBefore = config;
}

而这个回调函数也接受三个参数,所以我们的构造函数要进行更改:


function myrouter (obj) {
    
    
  this.mode = obj.mode || 'hash'
  this.saveBefore = null
  this.saveAfter = null
  this.from = ''
  this.to = ''
}

而我们不管在什么方法之中,都要时刻更新to和from的值(push,replace,go,监听方法)

而这个钩子函数的回调函数的第三个参数是传了一个next的回调函数(有点绕)

但是重点我们应该放在这个next的回调函数上,我们知道next方法可以接受参数的方式有三种:

true / false : 继续执行/ 停止执行
string : 跳转到某个路由
: 停止执行(或者不写next)

所以next方法中
我们要对参数进行类型判断,而对于每种类型我们还要对hash和history模式进行判断:

myrouter.prototype.next = function () {
    
    
  //当next中没有参数
  if (arguments[0] == undefined) {
    
    
    //判断路由模式
    if (this.mode == 'hash') {
    
    
      let str = location.origin + '/#' + this.to
      //判断是什么方法
      if (this.methodType == 'replace') {
    
    
        location.replace(str)
      } else if (this.methodType == 'push') {
    
    
        location.href = str
      }
      h1.innerHTML = str;
    } else if (this.mode = 'history') {
    
    
      let str = location.origin + this.to
      if (this.methodType == 'push') {
    
    
        history.pushState({
    
    }, '', str)
      } else if (this.methodType == 'replace') {
    
    
        history.replaceState({
    
    }, '', str)
      }
      h1.innerHTML = str;
    }
    this.from = this.to
  }
  //当next中参数是某个路径
  else if (typeof arguments[0] == 'string') {
    
    
    //判断路由模式
    if (this.mode == 'hash') {
    
    
      location.hash = arguments[0]
    } else if (this.mode = 'history') {
    
    
      let str = location.origin + arguments[0]
      //判断是什么方法
      if (this.methodType == 'push') {
    
    
        history.pushState({
    
    }, '', str)
      } else if (this.methodType == 'replace') {
    
    
        history.replaceState({
    
    }, '', str)
      }

      h1.innerHTML = str;
    }
    this.to = arguments[0]
  }
  //当next里面传入其他参数(false)或者没有使用next方法
  else {
    
    
    if (this.mode == 'hash') {
    
    
      location.hash = this.from
    } else if (this.mode = 'history') {
    
    
      if (this.from) {
    
    
        let str = location.origin + this.from
        if (this.methodType == 'push') {
    
    
          history.pushState({
    
    }, '', str)
        } else if (this.methodType == 'replace') {
    
    
          history.replaceState({
    
    }, '', str)
        }
      } else {
    
    
        history.back()
      }
    }
    this.to = this.from
  }
}

OK,next方法写好了之后,我们只需要在push,replace,go,监听的方法之中,判断this.saveBefore是否为空,如果不为空,我们就调用这个方法进行路由拦截。

5.router-link

其实实现出router-link的话,应该比较简单,我们直接自己封装出一个子组件,在main.js中引入其实就可。

其中主要有的就是父组件向子组件传值的问题:
在这里我就直接把代码拿过来了:

<template>
  <a @click="fn" class="routerlink">
    <slot></slot>
  </a>
</template>

<script>
import router from '../myrouter'

export default {
    
    
  name : 'routerLink',
  props : ['to','replace'],
  data(){
    
    
    return {
    
    
      title : 'router-link'
    }
  },
  created(){
    
    

  },
  methods : {
    
    
    fn(){
    
    
      if(this.to){
    
    
        this.$myrouter.push(this.to);
      }else if(this.replace){
    
    
        this.$myrouter.replace(this.replace)
      }
    }
  }
}
</script>

<style scoped>
  .routerlink{
    
    
    cursor:pointer
  }
</style>

6.router-view

router-view的实现需要考虑的可能就多一些,我们可以再实现一个子组件,然后把之前的h1标签替换成现在的子组件。

<template>
  <div class="routerview"></div>
</template>

但是这种情况我们不能实现嵌套路由。

所以我们的解决办法是:

对path和routers进行对应匹配,然后进行匹配的值的层记录下来,再对对应层的router-view进行渲染。

。。。。md说不明白。
emmm,这就要靠自己理解了。。。。

对于以上所以的方法和原理,因为要粘贴代码可能伴随着删减,可能出现问题,所以最后我把自己写的源码直接粘贴过来吧。

7.myrouter.js代码

import Vue from 'vue'

var routerview = document.getElementsByClassName('routerview')
function myrouter (obj) {
    
    
  this.mode = obj.mode || 'hash'
  this.saveBefore = null
  this.saveAfter = null
  this.from = ''
  this.to = ''
  this.methodType = ''
  this.routes = obj.routes;
}

myrouter.prototype.push = function (data) {
    
    
  this.methodType = 'push'
  let orgin = location.origin;
  //判断路由模式
  if (this.mode == 'hash') {
    
    
    this.to = ifObj(data)
    this.from = location.hash.replace('#', '');
    //判断是否使用路由拦截
    if (this.saveAfter) {
    
    
      this.saveAfter(this.to, this.from);
    }
    if (this.saveBefore) {
    
    
      this.saveBefore(this.to, this.from, this.next)
    } else {
    
    
      location.href = orgin + '/#' + ifObj(data);
      h1.innerHTML = returnView(ifObj(data), this.routes)
    }
  }
  else if (this.mode = 'history') {
    
    
    this.to = ifObj(data)
    this.from = location.pathname;
    if (this.saveAfter) {
    
    
      this.saveAfter(this.to, this.from);
    }
    if (this.saveBefore) {
    
    
      this.saveBefore(this.to, this.from, this.next)
    } else {
    
    
      history.pushState({
    
    }, '', orgin + ifObj(data))
      routerview.innerHTML = ''
      routerview.appendChild(returnView(ifObj(data).replace('/', ''), this.routes))
    }
  }
}

myrouter.prototype.go = function (num) {
    
    
  this.methodType = 'go'
  history.go(num)
}

myrouter.prototype.replace = function (data) {
    
    
  this.methodType = 'replace'
  let orgin = location.origin;
  //判断路由模式
  if (this.mode == 'hash') {
    
    
    //判断是否使用路由拦截
    if (this.saveAfter) {
    
    
      this.saveAfter(this.to, this.from);
    }
    if (this.saveBefore) {
    
    
      this.to = ifObj(data)
      this.from = location.hash.replace('#', '')
      this.saveBefore(this.to, this.from, this.next)
    } else {
    
    
      location.replace(orgin + '/#' + ifObj(data));
      routerview.innerHTML = ''
      routerview.appendChild(ifObj(data).replace('/', ''))
    }
  } else if (this.mode == 'history') {
    
    
    if (this.saveAfter) {
    
    
      this.saveAfter(this.to, this.from);
    }
    if (this.saveBefore) {
    
    
      this.to = ifObj(data)
      this.from = location.pathname;
      this.saveBefore(this.to, this.from, this.next)
    } else {
    
    
      history.replaceState({
    
    }, '', orgin + ifObj(data))
      routerview.innerHTML = ''
      routerview.appendChild(ifObj(data).replace('/', ''))
    }
  }
}

//钩子的next回调函数
myrouter.prototype.next = function () {
    
    
  //当next中没有参数
  if (arguments[0] == undefined) {
    
    
    //判断路由模式
    if (this.mode == 'hash') {
    
    
      let str = location.origin + '/#' + this.to
      //判断是什么方法
      if (this.methodType == 'replace') {
    
    
        location.replace(str)
      } else if (this.methodType == 'push') {
    
    
        location.href = str
      }
      let arr = this.to.split('/');
      let path = '/' + arr[arr.length - 1]
      let com = (ifChild(this.to, this.routes))

      // let path = ('/' + location.hash.replace('#', '').split('/').pop());
      // let com = (ifChild(location.hash.replace('#', ''), this.routes))
      routerview[routerview.length - 1].innerHTML = ''
      routerview[routerview.length - 1].appendChild(returnView(path, com))
    } else if (this.mode = 'history') {
    
    
      let str = location.origin + this.to
      if (this.methodType == 'push') {
    
    
        history.pushState({
    
    }, '', str)
      } else if (this.methodType == 'replace') {
    
    
        history.replaceState({
    
    }, '', str)
      }
      routerview.innerHTML = ''
      routerview.appendChild(returnView(location.pathname, this.routes))
    }
    this.from = this.to
  }
  //当next中参数是某个路径
  else if (typeof arguments[0] == 'string') {
    
    
    //判断路由模式
    if (this.mode == 'hash') {
    
    
      location.hash = arguments[0]
    } else if (this.mode = 'history') {
    
    
      let str = location.origin + arguments[0]
      //判断是什么方法
      if (this.methodType == 'push') {
    
    
        history.pushState({
    
    }, '', str)
      } else if (this.methodType == 'replace') {
    
    
        history.replaceState({
    
    }, '', str)
      }
      routerview.innerHTML = ''
      routerview.appendChild(returnView(location.pathname, this.routes))
    }
    this.to = arguments[0]
  }
  //当next里面传入其他参数(false)或者没有使用next方法
  else {
    
    
    if (this.mode == 'hash') {
    
    
      location.hash = this.from
    } else if (this.mode = 'history') {
    
    
      if (this.from) {
    
    
        let str = location.origin + this.from
        if (this.methodType == 'push') {
    
    
          history.pushState({
    
    }, '', str)
        } else if (this.methodType == 'replace') {
    
    
          history.replaceState({
    
    }, '', str)
        }
      } else {
    
    
        history.back()
      }
    }
    this.to = this.from
  }
}

//前置钩子函数(主要用于保存回调函数)
myrouter.prototype.beforeEach = function (config) {
    
    
  this.saveBefore = config;
}

//后置钩子函数
myrouter.prototype.afterEach = function (config) {
    
    
  this.saveAfter = config
}

//挂在在window上的监听方法
myrouter.prototype.update = function () {
    
    
  let _this = this;
  //判断路由模式
  if (this.mode == 'hash') {
    
    
    //监听url哈希值的变化
    window.onhashchange = function () {
    
    
      //判断是否使用路由拦截
      if (_this.saveAfter) {
    
    
        _this.saveAfter(_this.to, _this.from);
      }
      let length = location.hash.replace('#', '').split('/').length - 1;
      if (routerview[length]) {
    
    
        routerview[length].remove()
      }
      if (_this.saveBefore) {
    
    
        _this.to = location.hash.replace('#', '')
        _this.saveBefore(_this.to, _this.from, _this.next)
      } else {
    
    
        routerview.innerHTML = ''
        routerview.appendChild(returnView(location.hash.replace('#/', ''), this.routes))
      }
    }
    window.onload = function () {
    
    
      if (location.hash.length == 0) {
    
    
        location.href = location.origin + '/#' + location.pathname
      }
      if (_this.saveAfter) {
    
    
        _this.saveAfter(_this.to, _this.from)
      }
      let arr = location.hash.replace('#', '').split('/');
      arr.shift()
      let too = ''
      arr.forEach(val => {
    
    
        if (_this.saveBefore) {
    
    
          too += ('/' + val)
          _this.to = too
          _this.saveBefore(_this.to, _this.from, _this.next)
        } else {
    
    
          routerview.innerHTML = ''
          routerview.appendChild(returnView(location.hash.replace('#/', ''), this.routes))
        }
      })
    }
  }
  else if (this.mode == 'history') {
    
    
    //监听history模式下前进后退的操作
    window.addEventListener('popstate', function () {
    
    
      _this.methodType = 'go'
      //判断是否使用路由拦截
      if (_this.saveAfter) {
    
    
        _this.saveAfter(_this.to, _this.from);
      }
      if (_this.saveBefore) {
    
    
        _this.to = location.pathname
        _this.saveBefore(_this.to, _this.from, _this.next)
      } else {
    
    
        routerview.innerHTML = ''
        routerview.appendChild(returnView(location.pathname, this, routes))
      }
    });
    window.onload = function () {
    
    
      if (location.hash.length != 0) {
    
    
        location.href = location.href.replace('/#', '')
      }
      if (_this.saveAfter) {
    
    
        _this.saveAfter(_this.to, _this.from);
      }
      if (_this.saveBefore) {
    
    
        _this.to = location.pathname
        _this.saveBefore(_this.to, _this.from, _this.next)
      } else {
    
    
        routerview.innerHTML = ''
        routerview.appendChild(returnView(location.pathname, this.routes))
      }
    }
  }
}



//判断参数类型
function ifObj (data) {
    
    
  if (typeof data == 'object') {
    
    
    return data.path
  } else {
    
    
    return data;
  }
}

//通过路径path返回dom实例的方法
function returnView (path, routes) {
    
    
  // debugger
  if (path && routes) {
    
    
    for (var i = 0; i < routes.length; i++) {
    
    
      if (routes[i].path == path) {
    
    
        if (typeof routes[i].component.template == 'string') {
    
    
          let div = document.createElement('div');
          div.innerHTML = routes[i].component.template
          return div
        } else {
    
    
          return toDom(routes[i].component)
        }
      }
    }
  }
  var div = document.createElement('div');
  div.innerHTML = '<h1>404</h1>'
  return div
}

function ifChild (path, routes) {
    
    
  let arr = path.replace('/', '').split('/');
  return returnChild(arr, routes);
}

function returnChild (arr, routes) {
    
    
  if (arr && routes) {
    
    
    if (arr.length == 1) {
    
    
      for (var i = 0; i < routes.length; i++) {
    
    
        if (arr[0] == routes[i].path.replace('/', '')) {
    
    
          return routes
        }
      }
    } else {
    
    
      for (var i = 0; i < routes.length; i++) {
    
    
        if (arr[0] == routes[i].path.replace('/', '')) {
    
    
          arr.shift();
          return returnChild(arr, routes[i].children)
        }
      }
    }
  }
}

//将vue组建转换成dom的方法
function toDom (view) {
    
    
  const Instance = new Vue({
    
    
    render (h) {
    
    
      return h(view);
    }
  });

  const component = Instance.$mount();
  return component.$el
}
export default myrouter

8.main.js代码

import Vue from 'vue'
import App from './App.vue'
// import router from './router'
import myrouter from '../router/myrouter'
import view1 from '../router/view/view1.vue'
import view2 from '../router/view/view2.vue'
import child2 from '../router/view/child2.vue'

const a = {
    
     template: '<h1>a页面</h1>' }
const b = {
    
     template: '<h1>b页面</h1>' }

const child1 = {
    
     template: '<h1>child1页面</h1>' }

const routes = [
  {
    
    
    path: '/a', component: view2, children: [
      {
    
     path: '/achild1', component: child1 },
      {
    
     path: '/achild2', component: child2 }
    ]
  },
  {
    
     path: '/b', component: b },
  {
    
     path: '/c', component: view1 }
]

let router = new myrouter({
    
    
  mode: 'hash',
  routes: routes
})

router.beforeEach((to, from, next) => {
    
    
  // console.log(to, from);
  if (to == '/a') {
    
    
    router.next()
  } else if (to == '/b') {
    
    
    router.next()
  } else if (to == '/c') {
    
    
    router.next()
  } else if (to == '/d') {
    
    
    router.next()
  } else {
    
    
    router.next()
  }
})


router.afterEach((to, from) => {
    
    
  if (to == '/a' && from == '/b') {
    
    
    console.log('from b to a');
  }
})


Vue.prototype.$myrouter = router;
new Vue({
    
    
  el: '#app',
  render: h => h(App),
  // router,
})


猜你喜欢

转载自blog.csdn.net/weixin_46726346/article/details/119606892