vue源码分析(2)- 实例化

简介: vue源码分析(2)- 实例化

hello 大家好,我是 superZidan,这篇文章想跟大家聊聊 vue源码分析(2)- 实例化 ,如果大家遇到任何问题,欢迎 联系我 或者直接微信添加 superZidan41

背景

Vue.js是现在国内比较火的前端框架,希望通过接下来的一系列文章,能够帮助大家更好的了解Vue.js的实现原理。本次分析的版本是Vue.js2.5.16。(持续更新中。。。)

目录

Vue的实例化

由上一章我们了解了Vue类的定义,本章主要分析用户实例化Vue类之后,Vue.js框架内部做了具体的工作。

举个例子

var demo = new Vue({
   
  el: '#app',
  created(){
   },
  mounted(){
   },
  data:{
   
    a: 1,
  },
  computed:{
   
    b(){
   
      return this.a+1
    }
  },
  methods:{
   
    handleClick(){
   
      ++this.a ;
    }
  },
  components:{
   
    'todo-item':{
   
      template: '<li>to do</li>',
      mounted(){
   
      }
    }
  }
})

以上是一个简单的vue实例化的例子,用户通过new的方式创建了一个Vue的实例demo。所以我们先看看Vue的构造函数里面定义了什么方法。

src/core/instance/index.js

这个文件声明了Vue类的构造函数,构造函数中直接调用了实例方法_init来初始化vue的实例,并传入options参数。

import {
    initMixin } from './init'
import {
    stateMixin } from './state'
import {
    renderMixin } from './render'
import {
    eventsMixin } from './events'
import {
    lifecycleMixin } from './lifecycle'
import {
    warn } from '../util/index'

// 声明Vue类
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类传入各种初始化方法
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)

export default Vue

接下来我们看看这个_init方法具体做了什么事情。

src/core/instance/init.js

这个文件的initMixin方法定义了vue实例方法_init。

 Vue.prototype._init = function (options?: Object) {
   
    // this指向Vue的实例,所以这里是将Vue的实例缓存给vm变量
    const vm: Component = this
    // a uid
    // 每一个vm有一个_uid,从0依次叠加
    vm._uid = uid++

    let startTag, endTag
    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
   
      startTag = `vue-perf-start:${
     vm._uid}`
      endTag = `vue-perf-end:${
     vm._uid}`
      mark(startTag)
    }

    // a flag to avoid this being observed
    // 表示vue实例
    vm._isVue = true
    // merge options

    // 处理传入的参数,并将构造方法上的属性跟传入的属性合并(merge)

    // 处理子组件的options,后续讲到组件会详细展开
    if (options && options._isComponent) {
   
      // optimize internal component instantiation
      // since dynamic options merging is pretty slow, and none of the
      // internal component options needs special treatment.
      initInternalComponent(vm, options)
    } else {
   
      vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {
   },
        vm
      )
    }
    /* istanbul ignore else */
    // 添加vm的_renderProxy属性,非生产环境ES6的proxy代理,对非法属性获取进行提示
    if (process.env.NODE_ENV !== 'production') {
   
      initProxy(vm)
    } else {
   
      vm._renderProxy = vm
    }
    // expose real self
    // 添加vm的_self属性
    vm._self = vm
    // 对vm进行各种初始化


    // 将vm自身添加到该vm的父组件的的$children数组中
    // 添加vm的$parent,$root,$children,$refs,_watcher,_inactive,_directInactive,_isMounted,_isDestroyed,_isBeingDestroyed属性
    // 具体实现在 src/core/instance/lifecycle.js中,代码比较简单,不做展开
    initLifecycle(vm)

    // 添加vm._events,vm._hasHookEvent属性
    initEvents(vm)

    // 添加vm._vnode,vm._staticTrees,vm.$vnode,vm.$slots,vm.$scopedSlots,vm._c,vm.$createElement
    // 将vm上的$attrs,$listeners 属性设置为响应式的
    initRender(vm)

    // 触发beforeCreate钩子,如果options中有beforeCreate的回调函数,则会被调用
    callHook(vm, 'beforeCreate')

    initInjections(vm) // resolve injections before data/props

    // 初始化state,包括Props,methods,Data,Computed,watch;
    // 这块内容比较核心,所以会在下一章详细讲解,这里先大概描述一下
    // 对于prop以及data属性,将其设置为vm的响应式属性,即使用object.defineProperty绑定vm的prop和data属性并设置其getter&setter
    // 对于methods,则将每个method都挂载在vm上,并将this指向vm
    // 对于Computed,在将其设置为vm的响应式属性之外,还需要定义watcher,用于收集依赖
    // watch属性,也是将其设置为watcher实例,收集依赖
    initState(vm)

    // 初始化provide属性
    initProvide(vm) // resolve provide after data/props

    // 至此,所有数据的初始化工作已经做完,所有触发created钩子,在这个钩子的回调中可以访问之前所定义的所有数据
    callHook(vm, 'created')

    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
   
      vm._name = formatComponentName(vm, false)
      mark(endTag)
      measure(`vue ${
     vm._name} init`, startTag, endTag)
    }
    // 调用vm上的$mount方法
    if (vm.$options.el) {
   
      vm.{
   mathJaxContainer[5]}options.el)
    }
  }

接下来分析一下vm上的$mount方法具体做了什么事情

platforms/web/entry-runtime-with-compiler.js

// 缓存Vue.prototype上的$mount方法到变量mount上
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
   
  // 获取dom上的元素
  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') {
   
        if (template.charAt(0) === '#') {
   
          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) {
   
        template = template.innerHTML
      } else {
   
        if (process.env.NODE_ENV !== 'production') {
   
          warn('invalid template option:' + template, this)
        }
        return this
      }
    } else if (el) {
   
      template = getOuterHTML(el)
    }
    if (template) {
   
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
   
        mark('compile')
      }
      // 根据模板生成相关的render,staticRenderFns方法
      // 这块内容涉及的内容比较多,会在后面的其他章节中有详细讲解
      const {
    render, staticRenderFns } = compileToFunctions(template, {
   
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      // 将render,staticRenderFns方法添加到options上
      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')
      }
    }
  }
  // 调用前面缓存的mount方法
  return mount.call(this, el, hydrating)
}

接下来看看缓存的$mount方法的实现

platforms/web/runtime/index.js

Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
   
  // 获取相关的dom元素,执行mountComponent方法
  el = el && inBrowser ? query(el) : undefined
  return mountComponent(this, el, hydrating)
}

看看mountComponent方法的实现

export function mountComponent (
  vm: Component,
  el: ?Element,
  hydrating?: boolean
): Component {
   
  vm.$el = el
  if (!vm.$options.render) {
   
    vm.$options.render = createEmptyVNode
    if (process.env.NODE_ENV !== 'production') {
   
      /* istanbul ignore if */
      if ((vm.{
   mathJaxContainer[6]}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')
  // 设置updateComponent方法
  let updateComponent
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
   
    updateComponent = () => {
   
      const name = vm._name
      const id = vm._uid
      const startTag = `vue-perf-start:${
     id}`
      const endTag = `vue-perf-end:${
     id}`

      mark(startTag)
      const vnode = vm._render()
      mark(endTag)
      measure(`vue ${
     name} render`, startTag, endTag)

      mark(startTag)
      vm._update(vnode, hydrating)
      mark(endTag)
      measure(`vue ${
     name} patch`, startTag, endTag)
    }
  } else {
   
    updateComponent = () => {
   
      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

  // 创建watcher对象,具体watch的实现会在下一章详细分析
  // 简单描述一下这个过程:初始化这个watcher对象,执行updateComponent方法,收集相关的依赖
  // updateComponent的执行过程:
  // 先执行vm._render方法,根据之前生成的render方法,生成相关的vnode,也就是virtual dom相关的内容,这个会在后续渲染的章节详细讲解
  // 通过生成的vnode,调用vm._update,最终将vnode生成的dom插入到父节点中,完成组件的载入
  new Watcher(vm, updateComponent, noop, null, 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
    // 调用mounted钩子,在这个钩子的回调函数中可以访问到真是的dom节点,因为在上述过程中已经将真实的dom节点插入到父节点
    callHook(vm, 'mounted')
  }
  return vm
}

OK,以上就是Vue整个实例化的过程,多谢观看&欢迎拍砖。

目录
相关文章
|
8天前
|
JavaScript
Vue中如何实现兄弟组件之间的通信
在Vue中,兄弟组件可通过父组件中转、事件总线、Vuex/Pinia或provide/inject实现通信。小型项目推荐父组件中转或事件总线,大型项目建议使用Pinia等状态管理工具,确保数据流清晰可控,避免内存泄漏。
96 2
|
3月前
|
人工智能 JavaScript 算法
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
528 0
|
5月前
|
JavaScript
vue实现任务周期cron表达式选择组件
vue实现任务周期cron表达式选择组件
743 4
|
3月前
|
JavaScript UED
用组件懒加载优化Vue应用性能
用组件懒加载优化Vue应用性能
|
4月前
|
JavaScript 数据可视化 前端开发
基于 Vue 与 D3 的可拖拽拓扑图技术方案及应用案例解析
本文介绍了基于Vue和D3实现可拖拽拓扑图的技术方案与应用实例。通过Vue构建用户界面和交互逻辑,结合D3强大的数据可视化能力,实现了力导向布局、节点拖拽、交互事件等功能。文章详细讲解了数据模型设计、拖拽功能实现、组件封装及高级扩展(如节点类型定制、连接样式优化等),并提供了性能优化方案以应对大数据量场景。最终,展示了基础网络拓扑、实时更新拓扑等应用实例,为开发者提供了一套完整的实现思路和实践经验。
531 77
|
2月前
|
JavaScript 安全
在 Vue 中,如何在回调函数中正确使用 this?
在 Vue 中,如何在回调函数中正确使用 this?
100 0
|
2月前
|
人工智能 JSON JavaScript
VTJ.PRO 首发 MasterGo 设计智能识别引擎,秒级生成 Vue 代码
VTJ.PRO发布「AI MasterGo设计稿识别引擎」,成为全球首个支持解析MasterGo原生JSON文件并自动生成Vue组件的AI工具。通过双引擎架构,实现设计到代码全流程自动化,效率提升300%,助力企业降本增效,引领“设计即生产”新时代。
231 1
|
5月前
|
缓存 JavaScript 前端开发
Vue 基础语法介绍
Vue 基础语法介绍
|
3月前
|
JavaScript 前端开发 开发者
Vue 自定义进度条组件封装及使用方法详解
这是一篇关于自定义进度条组件的使用指南和开发文档。文章详细介绍了如何在Vue项目中引入、注册并使用该组件,包括基础与高级示例。组件支持分段配置(如颜色、文本)、动画效果及超出进度提示等功能。同时提供了完整的代码实现,支持全局注册,并提出了优化建议,如主题支持、响应式设计等,帮助开发者更灵活地集成和定制进度条组件。资源链接已提供,适合前端开发者参考学习。
362 17