摘要

前段时间对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,
})

到此这篇关于JavaScript封装Vue-Router实现流程详解的文章就介绍到这了,更多相关JS封装Vue-Router内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

JavaScript封装Vue-Router实现流程详解的更多相关文章

  1. 基于JavaScript编写一个图片转PDF转换器

    本文为大家介绍了一个简单的 JavaScript 项目,可以将图片转换为 PDF 文件。你可以从本地选择任何一张图片,只需点击一下即可将其转换为 PDF 文件,感兴趣的可以动手尝试一下

  2. HTML5数字输入仅接受整数的实现代码

    这篇文章主要介绍了HTML5数字输入仅接受整数的实现代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  3. amaze ui 的使用详细教程

    这篇文章主要介绍了amaze ui 的使用详细教程,本文通过多种方法给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  4. html5简介_动力节点Java学院整理

    这篇文章主要介绍了html5简介,用于指定构建网页的元素,这些元素中的大多数都用于描述网页内容,有兴趣的可以了解一下

  5. ios 8 Homescreen webapp,关闭和打开iPad停止javascript

    我有一个适用于iPad的全屏HTML5网络应用程序,并且刚刚安装了IOS8来试用它,它一切正常,直到你关闭并重新启动iPad.一旦web应用程序重新启动javascript就会停止并加载新页面不会重新启动它.在iPad上的Safari中打开同一页面时,关闭和打开iPad会继续按预期工作.其他人注意到了这个或想出了一个解决方案吗?解决方法这似乎是我在iOS8.1.1更新中解决的.

  6. iOS 6 javascript与object.defineProperty的间歇性问题

    当访问使用较新的Object.defineProperty语法定义属性的对象的属性时,有没有其他人注意到新iOS6javascript引擎中的间歇性错误/问题?https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty我正在看到javascript失败的情况,说

  7. ios – 如何使用JSExport导出内部类的方法

    解决方法似乎没有办法将内部类函数导出到javascript.我将内部类移出并创建了独立的类,它起作用了.

  8. 静音iOS推送通知与React Native应用程序在后台

    我有一个ReactNative应用程序,我试图获得一个发送到JavaScript处理程序的静默iOS推送通知.我看到的行为是AppDelegate中的didReceiveRemoteNotification函数被调用,但是我的JavaScript中的处理程序不会被调用,除非应用程序在前台,或者最近才被关闭.我很困惑的事情显然是应用程序正在被唤醒,并且它的didReceiveRemoteNotifi

  9. ios – 内存泄漏与UIWebView和Javascript

    清楚地包含一个Javascript文件到我的HTML是使UIWebView泄漏内存.当我重复使用相同的UIWebView对象时,或者每当我有内容实例化一个新的漏洞时,会出现泄漏的事实,导致我认为必须有一些JavaScript文件被loadHTMLString处理,导致泄漏.有人知道如何解决这个问题吗?

  10. iOS应用程序的UI自动化测试如何与乐器和Javascript

    从WWDC2010视频会议中了解iOS应用程序的自动化UI测试,但没有实践.从代码项目project,我们可以有一个例子.这个问题在这里听到有涉及这个的人.任何限制?解决方法我建议从AlexWollmer开始使用thisblogpost.他创建了一个非常有用的JavaScript库:tuneup_jswithtest()函数,它允许测试分离和有用的帮助者以及为自动化仪器编写测试的断言.

随机推荐

  1. js中‘!.’是什么意思

  2. Vue如何指定不编译的文件夹和favicon.ico

    这篇文章主要介绍了Vue如何指定不编译的文件夹和favicon.ico,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  3. 基于JavaScript编写一个图片转PDF转换器

    本文为大家介绍了一个简单的 JavaScript 项目,可以将图片转换为 PDF 文件。你可以从本地选择任何一张图片,只需点击一下即可将其转换为 PDF 文件,感兴趣的可以动手尝试一下

  4. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  5. AngularJs上传前预览图片的实例代码

    使用AngularJs进行开发,在项目中,经常会遇到上传图片后,需在一旁预览图片内容,怎么实现这样的功能呢?今天小编给大家分享AugularJs上传前预览图片的实现代码,需要的朋友参考下吧

  6. JavaScript面向对象编程入门教程

    这篇文章主要介绍了JavaScript面向对象编程的相关概念,例如类、对象、属性、方法等面向对象的术语,并以实例讲解各种术语的使用,非常好的一篇面向对象入门教程,其它语言也可以参考哦

  7. jQuery中的通配符选择器使用总结

    通配符在控制input标签时相当好用,这里简单进行了jQuery中的通配符选择器使用总结,需要的朋友可以参考下

  8. javascript 动态调整图片尺寸实现代码

    在自己的网站上更新文章时一个比较常见的问题是:文章插图太宽,使整个网页都变形了。如果对每个插图都先进行缩放再插入的话,太麻烦了。

  9. jquery ajaxfileupload异步上传插件

    这篇文章主要为大家详细介绍了jquery ajaxfileupload异步上传插件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. React学习之受控组件与数据共享实例分析

    这篇文章主要介绍了React学习之受控组件与数据共享,结合实例形式分析了React受控组件与组件间数据共享相关原理与使用技巧,需要的朋友可以参考下

返回
顶部