模拟实现一个vue-router

543 阅读1分钟

编程式导航

  • this.$router.repalce('path'), 不会记录历史
  • this.$router.push({name: '', params: {id: 1}}) ,会记录历史
  • this.$router.go(-2), 后退两步

Hash 和 history 模式的区别

两者路由都是客户端的实现方式,也就是当路径发生变化时不会向服务器发送请求,通过ajax 向远程发送请求

  1. 表现形式的区别 Hash 模式 music.163.com/#/playlist?… History 模式 music.163.com/playlist/31…
  2. 原理的区别 hash 模式 Vue Router 默认使用的是 hash 模式,使用 hash 来模拟一个完整的 URL,通过 onhashchange 监听路径的变化 History 模式 基于 History API
  3. 开启 History 模式
const router = new VueRouter({
 // mode: 'hash',
 mode: 'history',
 routes
})

history 模式-nodejs 服务

  • nodejs 服务不开启 history 的情况下,刷新页面,此时会向服务发送请求,结果服务器找不到对应的地址,就会返回一个 cannot Get xxx 的页面
  • 开启 history ,假设当前在xxx.html 页面,刷新页面,此时会向服务器请求,服务器端此时找不到请求的地址,那么就默认返回 index.html ,此时前端加载路由index,发现路由规则中存在xxx 的 路由,则完成刷新的效果

手写vue-router

创建一个VueRouter 类

  • options 用来记录路由规则的
  • data 是个通过Vue.observable 创建的响应式对象,存储当前的路由地址
  • routeMap 将options 中的路由规则通过键值对的形式存放到这里面,path 作为 键,component 作为 值
  • constructor , 构造函数,初始化以上三个变量
  • install 静态方法,实现VueRouter的安装
  • createRouteMap 实现路由的映射
  • initComponents 注册 router-link 和 router-view 两个组件

** install **

  /**
   * 创建install 静态方法
   * @param {vue 实例} Vue
   */
  static install (Vue) {
    // 1. 判断当前的实例是否已经安装过
    if (VueRouter.install.installled) {
      return
    }
    VueRouter.install.installled = true
    // 2. 把vue构造函数记录到全局变量,将来在 VueRouter的实例中要使用到vue,比如Vue.component()
    _Vue = Vue
    // 3. 把创建vue 实例传入的router对象注入到Vue 实例
    // 为了把 router 共享到所有的组件中,将其挂载到Vue 的原型上
    // 以下写法错误:由于this 指向的是VueRouter , 而不是 Vue实例
    // _Vue.prototype.$router = this.$options.router
    // 使用 混入 来解决
    _Vue.mixin({
      // 所有组件都混入这个beforeCreated
      beforeCreated () {
        // 只有vue实例需要挂载router,组件不挂载
        if (this.$options.router) { // 组件的options 中不会有router 对象
          // 此时 this 指向的是Vue 实例
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })
  }

构造函数

constructor (options) {
    this.options = options
    // data 是个响应式属性,存储的是当前的路由地址, 当路由发生变化的时候,要加载对应组件,所以要设计成一个响应式对象
    this.data = _Vue.observable({
      // 存储当前的路由
      current: '/'
    })
    // 把options 中的路由规则存储进来, key为路由地址path,value 为 组件名称
    this.routeMap = {}
  }

initRouteMap

  // 遍历options 中的所有的路由规则,将path 作为 键,component 作为 值,存放到routeMap这个对象中
  // 方便通过 路由地址,直接能够找到对应要渲染的组件
  initRouteMap () {
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

initComponents

 // 初始化router-link 和 router-view 这两个组件
  initComponents (Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      // 运行时编译器不能编译tempalte 模板,需要编写 render 函数
      // template: '<a :href="to"><slot></slot></a>'
      render (h) {
        return h(
          'a',
          {
            attrs: {
              href: this.to
            },
            on: {
              click: this.clickHandler
            }
          }, [this.$slot.default]
        )
      },
      methods: {
        clickHandler (e) {
          // 1. 将地址栏中的地址改成即将要跳转的路由地址
          history.pushState(this.to)
          // 2. 要将地址记录到routMap 的current 中
          this.$router.data.current = this.to
          e.preventDefault()
        }
      }
    })
    const self = this
    Vue.component('router-view', {
      render (h) {
        // 根据当前的路由地址在routeMap 中找到对应的组件
        const component = self.routeMap[self.data.current]
        // 将组件通过h函数交给虚拟Dom

        return h(component)
      }
    })
  }

initEvent

  initEvent () {
    // 注册popstate事件
    window.addEventLi
    stener('popstate', () => {
      // data 是个响应式对象,当点击浏览器中的前进或后退,只需从地址栏中取出路由地址,
      // 改变 data.current 即可完成组件的切换
      this.data.current = location.pathname
    })
  }