Vue.js - VueRouter的Hash与History模式 / 手写VueRouter

一. Hash与History模式

 Hash模式History模式
url地址外观http://localhost:8081/#/abouthttp://localhost:8080/about
原理基于锚点,监听锚点变化时触发的onhashchange事件基于HTML5的 history.pushState()方法,该方法会向浏览器历史记录中加入一条数据,会改变当前地址栏的地址,但不去加载新地址
兼容性 对于IE,IE10及以上才支持histroy.pushState()方法;需要在web服务器端设置对于找不到的页面也返回index.html页,否则刷新会404。

相关仓库:https://gitee.com/big-right-right/vue-router-and-history-config

二. 手写VueRouter

let _Vue = null

export default class VueRouter {
  static install (Vue) {
    console.log('my install !!!')
    console.log(this)
    // 1 判断当前插件是否已经被安装
    if (VueRouter.install.installed) {
      return
    }
    VueRouter.install.installed = true

    // 2 把Vue构造函数记录到全局变量
    _Vue = Vue

    // 3 把创建Vue实例时传入的router对象注入到Vue实例
    // 混入
    _Vue.mixin({
      beforeCreate () {
        if (this.$options.router) { // 非组件的Vue实例
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      },
    })
  }

  constructor (options) {
    this.options = options
    this.routeMap = {}
    // _Vue.observable 创建响应式对象 在访问数据以及写数据的时候能自动执行一些逻辑
    this.data = _Vue.observable({
      current: '/'
    })
  }

  init () {
    console.log('my init !!!')
    this.createRouteMap()
    this.initComponents(_Vue)
  }

  createRouteMap () {
    // 遍历所有的路由规则 把路由规则解析成键值对的形式 存入routeMap
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  initComponents (Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      /* template: '<a :href="to"><slot></slot></a>' */
      render (h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.clickHandler
          },
        }, this.$slots.default)
      },
      methods: {
        clickHandler (e) {
          history.pushState({}, '', this.to)
          this.$router.data.current = this.to
          e.preventDefault()
        }
      },
    })

    const self = this
    Vue.component('router-view', {
      render (h) {
        const component = self.routeMap[self.data.current]
        return h(component) // h函数用于生成虚拟dom
      }
    })
  }
}


本文 完。
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值