vue调试源码初始化及初次渲染过程

1. 下载vue源码

1. package.json中,修改name(任意名字,与vue项目中引vue.config.js和main.js一样),并将dev,dev:esm加上代码地图--sourcemap,想看完整版的vue源码执行yarn dev,运行时代码执行yarn dev:esm
"name": "fang-vue",
"scripts": {
    "dev": "rollup -w -c scripts/config.js --sourcemap --environment TARGET:web-full-dev",
    "dev:cjs": "rollup -w -c scripts/config.js --environment TARGET:web-runtime-cjs-dev",
    "dev:esm": "rollup -w -c scripts/config.js --sourcemap --environment TARGET:web-runtime-esm",
}
image.png
2. 与vue项目建立软连接

控制台输入

// 建立软连接
yarn link
3. 控制台执行 yarn dev 命令,启动项目

2. 创建一个vue项目

1. 修改 vue.config.js,添加别名 fang-vue$
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: {
    resolve: {
      alias: {
        // 输入想要引入的vue源码的路径,vue源码是dev时,vue.js;vue源码是dev:esm时,vue.runtime.esm.js
        "fang-vue$": "fang-vue/dist/vue.js"
      }
    }
  }
})

2. 修改main.js中引入的vue名
// 改为引入fang-vue
import Vue from 'fang-vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

3. 建立软连接

控制台输入

// fang-vue是修改完的名字
yarn link fang-vue
4. 在node_modules中可找到相对应的fang-vue
img1.jpg
5. 启动项目,yarn serve
6. 在谷歌源代码source中可看到源代码
image.png

3. 调试源码,使用tempalte模式,初始化过程

1. 源码中: core/instance/index.js ——vue构造函数,混入实例方法
// vue构造函数,为什么不使用class,为了后续给vue实例添加成员,下边的initMixin等
function Vue (options) {
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword')
  }
  this._init(options)
}

// 给Vue原型上混入相应成员
// 注册vm的_init()方法,初始化vm
initMixin(Vue)
// 注册vm的$data/$props/$set/$delete/$watch
stateMixin(Vue)
// 初始化事件相关方法
// $on/$once/$emit/$off
eventsMixin(Vue)
// 初始化生命周期相关的混入方法
// _updata/$forceUpdate/$destroy
lifecycleMixin(Vue)
// 混入render
// $nextTick/_render
renderMixin(Vue)

export default Vue
  • 在控制台watch(监视)中添加Vue的监听,执行后会添加上相对应的$data等


    image.png
2. core/index.js——给Vue构造函数添加静态方法
import Vue from './instance/index'
import { initGlobalAPI } from './global-api/index'
import { isServerRendering } from 'core/util/env'
import { FunctionalRenderContext } from 'core/vdom/create-functional-component'

//给vue构造函数添加静态方法
initGlobalAPI(Vue)

Object.defineProperty(Vue.prototype, '$isServer', {
  get: isServerRendering
})

Object.defineProperty(Vue.prototype, '$ssrContext', {
  get () {
    /* istanbul ignore next */
    return this.$vnode && this.$vnode.ssrContext
  }
})

// expose FunctionalRenderContext for ssr runtime helper installation
Object.defineProperty(Vue, 'FunctionalRenderContext', {
  value: FunctionalRenderContext
})

Vue.version = '__VERSION__'

export default Vue
image.png
3. platforms/web/runtime/index.js——关于平台的内容
  • 给Vue.options中注入v-model,v-show指令,transition,transition-group组件
  • 判断是否是浏览器,typeof window !== 'undefined'
// install platform runtime directives & components
// 将platformDirectives内容复制到Vue.options.directives
// 主要是v-model,v-show指令,transition,transition-group组件
extend(Vue.options.directives, platformDirectives)
extend(Vue.options.components, platformComponents)

// install platform patch function
// patch将Vdom转为真实dom,怎么判断inBrowser
Vue.prototype.__patch__ = inBrowser ? patch : noop
image.png
4. platforms/web/entry-runtime-with-compiler.js——重写$mount方法,能够编译模板
// 重写$mount方法,能够编译模板
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(el)

  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }

  const options = this.$options
  // resolve template/el and convert to render function
  if (!options.render) {
    let template = options.template
    ......
  }
  return mount.call(this, el, hydrating)
}
......
// 注册Vue.complier方法,传递一个HTML字符串返回render函数
Vue.compile = compileToFunctions

4. 调试源码,初次渲染

1. Vue初始化,实例成员,静态成员
2. core/instance/index.js——this._init()——相当于入口
// vue构造函数,为什么不使用class,为了后续给vue实例添加成员,下边的initMixin等
function Vue (options) {
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword')
  }
  this._init(options)
}
  • this._init()方法最终定义了$mount
3. platforms/web/entry-runtime-with-compiler.js——vm.mount()——重写了mount()
// 重写$mount方法,能够编译模板
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(el)

  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }

  const options = this.$options
  // resolve template/el and convert to render function
  if (!options.render) {
    let template = options.template
    if (template) {
      if (typeof template === 'string') {
        // 如果模板是id选择器
        if (template.charAt(0) === '#') {
          // 获取对应的DOM对象的innerHTML
          template = idToTemplate(template)
          /* istanbul ignore if */
          if (process.env.NODE_ENV !== 'production' && !template) {
            warn(
              `Template element not found or is empty: ${options.template}`,
              this
            )
          }
        }
      } else if (template.nodeType) {
        // 有nodeType说明是dom元素,直接返回innerHTML,将innerHTML作为模板
        template = template.innerHTML
      } else {
        if (process.env.NODE_ENV !== 'production') {
          warn('invalid template option:' + template, this)
        }
        return this
      }
    } else if (el) {
      // 如果没有template,获取el的outerHTML,作为模板
      template = getOuterHTML(el)
    }
    if (template) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }
      // compileToFunctions将模板编译为render函数
      const { render, staticRenderFns } = compileToFunctions(template, {
        outputSourceRange: process.env.NODE_ENV !== 'production',
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns

      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile end')
        measure(`vue ${this._name} compile`, 'compile', 'compile end')
      }
    }
  }
  return mount.call(this, el, hydrating)
}

/**
 * Get outerHTML of elements, taking care
 * of SVG elements in IE as well.
 */
function getOuterHTML (el: Element): string {
  if (el.outerHTML) {
    return el.outerHTML
  } else {
    const container = document.createElement('div')
    container.appendChild(el.cloneNode(true))
    return container.innerHTML
  }
}
// 注册Vue.complier方法,传递一个HTML字符串返回render函数
Vue.compile = compileToFunctions

export default Vue
  • 判断有无render

  • 没有的话,判断有无template
    a. 有

    1. 判断是不是字符串,是字符串并且是id选择器,获取相对应的DOM对象的innerHTML
    2. 有nodeType的话,说明是dom元素,直接返回innerHTML,将innerHTML作为模板
    3. 返回this

    b. 无

    1. 返回el.outerHTML,作为模板
  • 有了template,通过compileToFunctions将模板编译为render函数
    编译完后: options.render = render

4. platforms/web/runtime/index.js——vm.$mount()——执行mountComponent
// public mount method
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && inBrowser ? query(el) : undefined
  // 重新获取el,如果是运行时版本,不会执行这个入口
  return mountComponent(this, el, hydrating)
}
  • 重新获取el,如果是运行时版本,不会执行这个入口
5. core/instance/lifecycle.js——mountComponent(this,el,..)——定义updateComponent()方法
export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
  vm.$el = el
  if (!vm.$options.render) {
    vm.$options.render = createEmptyVNode
    // 判断是否有render,没有但是传入了模板并且是开发环境,发出警告:运行版本(runtime-only)不支持tempalte
    if (process.env.NODE_ENV !== 'production') {
      /* istanbul ignore if */
      if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
        vm.$options.el || el) {
        warn(
          'You are using the runtime-only build of Vue where the template ' +
          'compiler is not available. Either pre-compile the templates into ' +
          'render functions, or use the compiler-included build.',
          vm
        )
      } else {
        warn(
          'Failed to mount component: template or render function not defined.',
          vm
        )
      }
    }
  }
  // 触发beforeMount钩子
  callHook(vm, 'beforeMount')

  let updateComponent
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
    // 性能检测代码
    ......
  } else {
    updateComponent = () => {
      // 执行完此句后会将template转换为render,_update将虚拟DOM转为真实DOM,把模板渲染到界面上,现在只是定义,还未执行
      // _render()作用是调用用户传入的render或编译template生成的render,返回VNode,把结果传入给_render
      vm._update(vm._render(), hydrating)
    }
  }

  // we set this to vm._watcher inside the watcher's constructor
  // since the watcher's initial patch may call $forceUpdate (e.g. inside child
  // component's mounted hook), which relies on vm._watcher being already defined
  // updateComponent传递
  new Watcher(vm, updateComponent, noop, {
    before () {
      if (vm._isMounted && !vm._isDestroyed) {
        callHook(vm, 'beforeUpdate')
      }
    }
  }, true /* isRenderWatcher */)
  hydrating = false

  // manually mounted instance, call mounted on self
  // mounted is called for render-created child components in its inserted hook
  if (vm.$vnode == null) {
    vm._isMounted = true
    // 页面挂载完毕
    callHook(vm, 'mounted')
  }
  return vm
}
  • 判断是否有render,没有但是传入了模板并且是开发环境,发出警告:运行版本(runtime-only)不支持tempalte
  • 触发beforeMount钩子
  • 定义updateComponent,vm._update(vm._render(), hydrating),此时还未执行
    _update将虚拟DOM转为真实DOM,把模板渲染到界面上
  • 向下 new Watcher()实例,updateComponent传递,进入watcher
6. core/observer/watcher.js——watcher()方法——调用get()方法
if (options) {
  ......
  // 是否延迟更新视图,渲染的是立即执行,即lazy:false,计算属性的话是true
  this.lazy = !!options.lazy
  ......
} else {
  ......
}
......
// 渲染时,第二个参数是函数,直接赋值getter
if (typeof expOrFn === 'function') {
  this.getter = expOrFn
} else {
  // 当wacther是侦听器时,第二个参数会传入字符串
  this.getter = parsePath(expOrFn)
  if (!this.getter) {
    this.getter = noop
    process.env.NODE_ENV !== 'production' && warn(
      `Failed watching path: "${expOrFn}" ` +
      'Watcher only accepts simple dot-delimited paths. ' +
      'For full control, use a function instead.',
      vm
    )
  }
}
this.value = this.lazy
  ? undefined
  : this.get()
  • 当wacther是侦听器时,第二个参数会传入字符串
  • lazy是否延迟更新视图,渲染的是立即执行,即lazy:false,计算属性的话是true
  • 执行this.get()方法
7. core/observer/watcher.js——get()方法——实际调用updateComponent位置
get () {
  pushTarget(this)
  let value
  const vm = this.vm
  try {
    // 实际调用updateComponent位置
    value = this.getter.call(vm, vm)
  } catch (e) {
   ......
  } finally {
   ......
  }
  return value
}
  • 调用updateComponent
  • 调用core/instance/lifecycle.js中vm._render()
  • 调用core/instance/lifecycle.js中vm._update()
8. 触发mounted钩子,挂载完毕

5. watcher

1. 有三种
  • 渲染watcher
  • 计算属性watcher(computed)
  • 用户watcher(侦听器)(watch)
2. 创建顺序,执行顺序都是这个

计算属性watcher->用户watcher(侦听器)->渲染watcher

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容