项目中使用vue-router的时候,会进行以下操作(可能具体不是这么写的,但是原理一样):

  1.   定义映射关系routes;
  2.   定义router实例的时候传入vue和参数{routes…};
  3.   定义vue实例的时候,把router挂载到vue实例上。

  

  接下来看我们写一个极简版的router源码。
  1. class VueRouter {
  2. constructor(Vue, options) {
  3. this.$options = options
  4. this.routeMap = {}
  5. this.app = new Vue({
  6. data: {
  7. current: \'#/\'
  8. }
  9. })
  10. this.init()
  11. this.createRouteMap(this.$options)
  12. this.initComponent(Vue)
  13. }
  14. // 初始化 hashchange
  15. init() {
  16. window.addEventListener(\'load\', this.onHashChange.bind(this), false)
  17. window.addEventListener(\'hashchange\', this.onHashChange.bind(this), false)
  18. }
  19. createRouteMap(options) {
  20. options.routes.forEach(item => {
  21. this.routeMap[item.path] = item.component
  22. })
  23. }
  24. // 注册组件
  25. initComponent(Vue) {
  26. Vue.component(\'router-link\', {
  27. props: {
  28. to: String
  29. },
  30. template: \'<a :href="to"><slot></slot></a>\'
  31. })
  32. const _this = this
  33. Vue.component(\'router-view\', {
  34. render(h) {
  35. var component = _this.routeMap[_this.app.current]
  36. return h(component)
  37. }
  38. })
  39. }
  40. // 获取当前 hash 串
  41. getHash() {
  42. return window.location.hash.slice(1) || \'/\'
  43. }
  44. // 设置当前路径
  45. onHashChange() {
  46. this.app.current = this.getHash()
  47. }
  48. }

  constructor里接受参数option并作为成员属性保存下来。定义routeMap用来保存路由和组件的map结构。定义vue的实例app让current动态化。

  初始化init()里监听浏览器的load和hashchange事件,当发生load和hashChange事件时触发onHashChange函数,并bind了this为当前路由器的实例。
  onHashChange()做的事情是获取地址栏里的地址赋值给current。
  createRouteMap()遍历传进来的options,生成routeMap
  initComponent()初始化router的组件<router-link/>,<router-view/>,把router-link渲染成一个a标签,<router-view> 用render函数渲染 则根据current和routeMap渲染当前路由对应的组件。

版权声明:本文为superlizhao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/superlizhao/p/10994447.html