优秀的编程知识分享平台

网站首页 > 技术文章 正文

Vue 源码阅读2之从0到beforeCreated

nanyue 2024-09-06 20:23:46 技术文章 7 ℃

Hello,大家好。现在咱们正式进入Vue源码阅读的主体部分。当网页中存在Vue文件在浏览器中运行的时候,Vue的环境已经存在于浏览器中。

当我们在其他脚本中执行var vm=new Vue(.....)时将会开始了Vue对象的一生。

(1)执行上述程序的时候将会调用Vue源代码目录下的/src/core/instance/index.js的Vue函数。这个函数主要的作用是调用Vue原型链上的_init函数以实现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)
}

(2)Vue原型链上的_init函数由源代码目录下的/src/core/instance/init.js的initMixin函数实现,从截取的这一部分代码我们看到最后调用了beforecreated的钩子函数,表明进入到了beforecreated过程。

也就是从调用_init函数到beforecreated之间进行了

1.设置vm的值为this值即Vue对象

2.设置Vue对象的ID号

3.设置对象的_isVue属性为真

4.将创建vue的参数与option属性进行合并。

5.初始化生命周期

6.初始化事件处理

7.初始化渲染器

8.使用callhook函数调用beforeCreated函数

const vm: Component = this
    vm._uid = uid++
    let startTag
    let endTag
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      startTag = `vue-perf-start:${vm._uid}`
      endTag = `vue-perf-end:${vm._uid}`
      mark(startTag)
    }
    vm._isVue = true
    if (options && options._isComponent) {
      initInternalComponent(vm, options)
    } else {
      vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )
    }
    if (process.env.NODE_ENV !== 'production') {
      initProxy(vm)
    } else {
      vm._renderProxy = vm
    }
    vm._self = vm
    initLifecycle(vm)
    initEvents(vm)
    initRender(vm)
    callHook(vm, 'beforeCreate')
最近发表
标签列表