Vue.js 源码学习笔记2 数据驱动

数据驱动

Vue.js 一个核心思想就是数据驱动

类比:

jquery缺点:直接操作dom 增加内存使用(把DOM与javascript各自想象成为岛屿,它们之间用收费桥梁链接的。访问DOM次数越多,费用就越高,推荐的做法是尽可能的减少过桥的次数,努力呆在ECMscript岛屿上。)

new Vue 时到底干了啥

new关键字在 Javascript 语言中代表实例化是一个对象,而 Vue 实际上是一个类,类在 Javascript 中是用 Function 来实现的

源码,在src/core/instance/index.js中

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)

}

new初始化vue后  再调用  this._init() 方法 在src/core/instance/init.js

Vue.prototype._init = function (options?: Object) {

  const vm: Component = this

  // a uid

  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

  vm._isVue = true

  // 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 */

  if (process.env.NODE_ENV !== 'production') {

    initProxy(vm)

  } else {

    vm._renderProxy = vm

  }

  // expose real self

  vm._self = vm

  initLifecycle(vm)

  initEvents(vm)

  initRender(vm)

  callHook(vm, 'beforeCreate')

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

  initState(vm)

  initProvide(vm) // resolve provide after data/props

  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)

  }

  if (vm.$options.el) {

    vm.$mount(vm.$options.el)

  }

}

Vue 初始化主要就干了几件事情,合并配置,初始化生命周期,初始化事件中心,初始化渲染,初始化 data、props、computed、watcher 等等

在初始化的最后,检测到如果有 el 属性,则调用 vm.$mount 方法挂载 vm,挂载的目标就是把模板渲染成最终的 DOM

initState() 做了什么事情

initData 拿出 vue 中data里的数据  赋值给 vm._data 同时拿到props 和 methods。 

最终使用proxy函数将 数据进行代理  例如:this.message =>  this._data.message

function initData (vm: Component) {

  let data = vm.$options.data

  data = vm._data = typeof data === 'function'

    ? getData(data, vm)

    : data || {}

  if (!isPlainObject(data)) {

    data = {}

    process.env.NODE_ENV !== 'production' && warn(

      'data functions should return an object:\n' +

      'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',

      vm

    )

  }

  // proxy data on instance

  const keys = Object.keys(data)

  const props = vm.$options.props

  const methods = vm.$options.methods

  let i = keys.length

  while (i--) {

    const key = keys[i]

    if (process.env.NODE_ENV !== 'production') {

      if (methods && hasOwn(methods, key)) {

        warn(

          `Method "${key}" has already been defined as a data property.`,

          vm

        )

      }

    }

    if (props && hasOwn(props, key)) {

      process.env.NODE_ENV !== 'production' && warn(

        `The data property "${key}" is already declared as a prop. ` +

        `Use prop default value instead.`,

        vm

      )

    } else if (!isReserved(key)) {

      proxy(vm, `_data`, key)

    }

  }

  // observe data

  observe(data, true /* asRootData */)

}

Vue 实例挂载的实现

Vue 中我们是通过 $mount 实例方法去挂载 vm 的,$mount 方法在多个文件中都有定义,如 src/platform/web/entry-runtime-with-compiler.js、src/platform/web/runtime/index.js、src/platform/weex/runtime/index.js。因为 $mount 这个方法的实现是和平台、构建方式都相关的。

当 抛开 webpack 的 vue-loader 。  compiler  是最接近我们本地开发的构建  在入口文件init.js中 使用$mounted() 方法进行挂载DOM时 就使用了这个方法

const mount = Vue.prototype.$mount

// 之前已经定义过的$mount方法 在文件入口处再次重新定义

Vue.prototype.$mount = function (

  el?: string | Element,

  hydrating?: boolean

): Component {

  el = el && query(el)


  /* istanbul ignore if */

  // 它对 el 做了限制,Vue 不能挂载在 body、html 这样的根节点上 vue本事会带html和body节点 会导致覆盖节点 提示报错  这也就是平常开发中为何使用<div id="app"></div>的方式来挂载vue

  if (el === document.body || el === document.documentElement) {

    process.env.NODE_ENV !== 'production' && warn(

      `Do not mount Vue to or - mount to normal elements instead.`

    )

    return this

  }


  const options = this.$options

  // resolve template/el and convert to render function

  // 如果没有定义 render 方法,则会把 el 或者 template 字符串转换成 render 方法

  // 在 Vue 2.0 版本中,所有 Vue 的组件的渲染最终都需要 render 方法,无论我们是用单文件 .vue 方式开发组件,还是写了 el 或者 template 属性,最终都会转换成 render 方法,那么这个过程是 Vue 的一个“在线编译”的过程,它是调用 compileToFunctions 方法实现的

  if (!options.render) {

    let template = options.template

    // 如果么有render 那么就读取template 并且对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是DOM对象 则获取html

        template = template.innerHTML

      } else {

        if (process.env.NODE_ENV !== 'production') {

          warn('invalid template option:' + template, this)

        }

        return this

      }

    } else if (el) { // 如果template 木有DOM innerHTML 则会在外面包一个

      template = getOuterHTML(el)

    }


    // 编译相关

    if (template) {

      /* istanbul ignore if */

      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {

        mark('compile')

      }


      const { render, staticRenderFns } = compileToFunctions(template, {

        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)

}


原先原型上的 $mount 方法在 src/platform/web/runtime/index.js 中定义,之所以这么设计完全是为了复用,因为它是可以被 runtimeonly 版本的 Vue 直接使用的。

Vue.prototype.$mount = function (

  el?: string | Element,

  hydrating?: boolean

): Component {

  el = el && inBrowser ? query(el) : undefined

  return mountComponent(this, el, hydrating)

}

$mount 方法支持传入 2 个参数,第一个是 el,它表示挂载的元素,可以是字符串,也可以是 DOM 对象,如果是字符串在浏览器环境下会调用 query 方法转换成 DOM 对象的。第二个参数是和服务端渲染相关,在浏览器环境下我们不需要传第二个参数。

$mount 方法实际上会去调用 mountComponent 方法,这个方法定义在 src/core/instance/lifecycle.js 文件中:

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.$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

        )

      }

    }

  }

  callHook(vm, 'beforeMount')


  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

  new Watcher(vm, updateComponent, noop, {

    before () {

      if (vm._isMounted) {

        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

}

从上面的代码可以看到,mountComponent 核心就是先调用 vm._render 方法先生成虚拟 Node,再实例化一个渲染Watcher,在它的回调函数中会调用 updateComponent 方法,最终调用 vm._update 更新 DOM。

Watcher 在这里起到两个作用,一个是初始化的时候会执行回调函数,另一个是当 vm 实例中的监测的数据发生变化的时候执行回调函数,

函数最后判断为根节点的时候设置 vm._isMounted 为 true, 表示这个实例已经挂载了,同时执行 mounted 钩子函数。 这里注意 vm.$vnode 表示 Vue 实例的父虚拟 Node,所以它为 Null 则表示当前是根 Vue 的实例。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,158评论 4 370
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,600评论 1 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,785评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,655评论 0 220
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,075评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,002评论 1 225
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,146评论 2 318
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,918评论 0 211
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,671评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,838评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,318评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,636评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,343评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,187评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,982评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,126评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,934评论 2 279

推荐阅读更多精彩内容

  • Vue 是通过$mount实例方法去挂载vm的,$mount方法在多个文件中都有定义,如src/platform/...
    famingng阅读 7,068评论 0 3
  • 这篇笔记主要包含 Vue 2 不同于 Vue 1 或者特有的内容,还有我对于 Vue 1.0 印象不深的内容。关于...
    云之外阅读 4,994评论 0 29
  • # 传智播客vue 学习## 1. 什么是 Vue.js* Vue 开发手机 APP 需要借助于 Weex* Vu...
    再见天才阅读 3,483评论 0 6
  • 没有人不是一座空城 到了夜晚总叫人心疼 心房空荡四肢冰冷 尽管开着全部的灯 我还是感到恐惧冰冷 我是一座空荡荡的新...
    若风在野阅读 160评论 0 2
  • 许多初学写作者都有这样的体会,心里想的挺好,然而一提笔满不是那么回事,无论怎样搅尽脑汁,挖空心思也写不出几个字来,...
    侯永生阅读 275评论 2 7