zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

如何吃透 vue-router

2023-03-20 14:51:48 时间

vue-router 是vue的插件,是对 vue的前端路由管理器,使用中通常分为hashhistory模式。

  • hash 模式
    • URL 中 # 后面的内容作为路径地址,只修改路径地址的话浏览器不会向服务器发送请求,只会将当前路径存放在history里
    • 通过监听 hashchange 事件,获取 hash 变化,按照配置加载不同的组件
  • history 模式
    • 通过 history.pushState() 方法改变地址栏,同样也不会向服务器发送请求,只会存放到history里
    • 监听 popstate 事件,当我们 history.back()、history.forward()、浏览器前进后退的时候回触发该事件,然后通过配置找到不同的组件重新渲染

首先我们通过使用的角度来观察vue-router有哪些基本信息

import Vue from "vue";
import Router from "vue-router";
// 注册插件
Vue.use(Router);
// 实例化
const router = new Router({
  mode: "history",
  routes: [
     {
        path: "/",
        name: "index",
        component: () => import("./views/layout/index.vue");
     },
  ]
})
// 创建 vue 实例,注册 router 对象
new Vue({
    router,
    render: h => h(App)
}).$mount("#app");
  • 注册插件
  • 实例化 vue-router,初始化配置
  • 创建vue实例,注册router对象

我们可以得到 vue-router 是个类,对外有暴露一个 install 方法,并且是一个静态方法,并且 constructor 有属性接受 插件配置

我们再通过源码看 vue-router 的基本属性以及方法

属性: options: 用来记录构造函数中传入的对象 data: 是个对象,里面有个 current 属性用来记录当前的路由地址,通过调用vue.observable来实现其响应式 routeMap: 用来记录路由对象与组件的映射关系 方法: constructor(options): 构造函数 install(Vue): 静态方法,用来注册插件 init(): 初始化,调用下列方法 initEvent(): 注册 popstate 方法,监听浏览器地址变化 createRouteMap(): 初始化routeMap initComponents(vue): 创建 router-link, router-view 组件

使用vue-cli 初始化项目,修改import 地址即可

实现 install 静态方法

  • 插件只需安装一次
  • 为方便 vue-router 实例方法使用 Vue 的方法,需要将 Vue 构建函数做全局存储 let _Vue = null export default class VueRouter { static install (Vue) { // 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 中执行,其他组件 $options.router 不存在,保证以下代码执行一次 _Vue.prototype.$router = this.$options.router } } }) } }

实现 constructor

  constructor (options) {
    this.options = options
    this.data = _Vue.observable({
      current: '/'
    })
    this.routeMap = {}
  }

实现 createRouteMap

我们刚才说过 createRouteMap 的作用是将 options 中传入的 routes 路由规则 转换为键值对的形式存储到 routeMap 中

  createRouteMap () {
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

实现 initComponents

首先创建 route-link 组件 <router-link to="/">Home</router-link> router-link 中的 to相当于一个超链接,并且内部的内容相当于a标签内部的内容

  initComponents (Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      template: '<a :href="to"><slot></slot></a>'
    })
  }

这个时候我们可以 先把我们的 init 方法也顺便实现了

  init () {
    this.createRouteMap()
    this.initComponents(_Vue)
  }

调用init的时候在 我们 install 中 混入的最后,然后我们就得到了

let _Vue = null
​
export default class VueRouter {
  constructor (options) {
    this.options = options
    this.data = _Vue.observable({
      current: '/'
    })
    this.routeMap = {}
  }
​
  createRouteMap () {
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }
​
  init () {
    this.createRouteMap()
    this.initComponents(_Vue)
  }
​
  initComponents (Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      template: '<a :href="to"><slot></slot></a>'
    })
  }
​
  static install (Vue) {
    // 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 中执行,其他组件 $options.router 不存在,保证以下代码执行一次
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })
  }
}

然后我们修改import 导入的 vuerouter 插件后 运行项目,发现

image.png

"您使用的是Vue的仅运行时构建,而模板编译器不可用。要么将模板预编译为呈现函数,要么使用包含编译器的构建。"

出现这个问题就涉及到了vue的构建版本的差异。

我们的使用cli 运行项目的时候,使用的是vue的运行时版本构建的,它不支持template模板编译,需要打包的时候提前编译。而完整版包含了运行时版本和编译器,在运行的时候会把模板转换成render函数,因此体积比运行时版本大10KB左右。

针对这种情况 Vue 官方已经给出我们解决的方案(参考链接),只需要我们在vue.config.js中,将 runtimeCompiler 设置成 true 即可。

除此之外我们还可以自己去使用 render 渲染模板。

  initComponents (Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      // template: '<a :href="to"><slot></slot></a>'
      render (h) { // h 是一个函数用来创建虚拟dom
        return h('a', {
          attrs: {
            href: this.to // history 模式
          }
        }, [this.$slots.default])
      }
    })
  }

继续创建 route-view 组件 我们route-view 组件的内容已经存储在 routeMap 里了,所以只需要我们将其取出转换成 vDom 即可

  initComponents (Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      // template: '<a :href="to"><slot></slot></a>'
      render (h) { // h 是一个函数用来创建虚拟dom
        return h('a', {
          attrs: {
            href: this.to // history 模式
          }
        }, [this.$slots.default])
      }
    })
​
    const _this = this // 记录 当前 vuerouter 对象
    Vue.component('router-view', {
      render (h) {
        const component = _this.routeMap[_this.data.current]
        return h(component)
      }
    })
  }

这个时候我们满心以为我们的vue-router 基本功能已经完成的时候,突然想到了我们忽略了一件事儿,因为我们之前的route-link 使用的 a标签 本身的默认事件是跳转并且从服务器请求。因此需要我们给 route-link 做一下改造。

  initComponents (Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      // template: '<a :href="to"><slot></slot></a>'
      render (h) { // h 是一个函数用来创建虚拟dom
        return h('a', {
          attrs: {
            href: this.to // history 模式
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler (e) {
          history.pushState({/* 传递给 popstate 参数 */}, '', this.to) // 改变地址栏
          this.$router.data.current = this.to // 改变current 重新出发渲染
          e.preventDefault()
        }
      }
    })
​
    const _this = this // 记录 当前 vuerouter 对象
    Vue.component('router-view', {
      render (h) {
        const component = _this.routeMap[_this.data.current]
        return h(component)
      }
    })
  }

截止到现在我们的基本功能已经可以使用了,但是我们发现之前提到过的 initEvent 没有实现,他的作用是注册 popstate 方法,监听浏览器地址变化,我们点击前进后退的时候就会发现 页面没有变化。因此我们还需要实现initEvent。

  initEvent () {
    window.addEventListener('popstate', () => { // 箭头函数不改变this指向
      this.data.current = window.location.pathname
    })
  }

现在我们完善了我们的代码,奉上

let _Vue = null
​
export default class VueRouter {
  constructor (options) {
    this.options = options
    this.data = _Vue.observable({
      current: '/'
    })
    this.routeMap = {}
  }
​
  createRouteMap () {
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }
​
  init () {
    this.createRouteMap()
    this.initComponents(_Vue)
    this.initEvent()
  }
​
  initComponents (Vue) {
    Vue.component('router-link', {
      props: {
        to: String
      },
      // template: '<a :href="to"><slot></slot></a>'
      render (h) { // h 是一个函数用来创建虚拟dom
        return h('a', {
          attrs: {
            href: this.to // history 模式
          },
          on: {
            click: this.clickHandler
          }
        }, [this.$slots.default])
      },
      methods: {
        clickHandler (e) {
          history.pushState({/* 传递给 popstate 参数 */}, '', this.to) // 改变地址栏
          this.$router.data.current = this.to // 改变current 重新出发渲染
          e.preventDefault()
        }
      }
    })
​
    const _this = this // 记录 当前 vuerouter 对象
    Vue.component('router-view', {
      render (h) {
        const component = _this.routeMap[_this.data.current]
        return h(component)
      }
    })
  }
​
  initEvent () {
    window.addEventListener('popstate', () => { // 箭头函数不改变this指向
      this.data.current = window.location.pathname
    })
  }
​
  static install (Vue) {
    // 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 中执行,其他组件 $options.router 不存在,保证以下代码执行一次
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })
  }
}