前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >你想要的——vue源码分析(2)

你想要的——vue源码分析(2)

原创
作者头像
can4hou6joeng4
发布于 2023-11-30 06:04:27
发布于 2023-11-30 06:04:27
1710
举报

背景

--

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

目录

--

  • Vue.js的引入
  • Vue的实例化
  • Vue数据处理(未完成)
  • 。。。

Vue的实例化


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

举个例子

代码语言:txt
AI代码解释
复制
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参数。

代码语言:txt
AI代码解释
复制
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。

代码语言:txt
AI代码解释
复制
 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.$mount(vm.$options.el)
    }
  }

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

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

代码语言:txt
AI代码解释
复制
// 缓存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

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

看看mountComponent方法的实现

代码语言:txt
AI代码解释
复制
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
        )
      }
    }
  }
  // 调用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整个实例化的过程,多谢观看&欢迎拍砖。

我正在参与2023腾讯技术创作特训营第三期有奖征文,组队打卡瓜分大奖!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
vue源码解读(二)
vue的核心思想是数据驱动。所谓数据驱动,就是指视图是由数据驱动生成的,想要对视图进行修改,不会直接操作DOM,而是通过修改数据。这样,我们在开发时候只需要关注数据的修改,DOM变成了数据的映射。
用户3258338
2019/07/19
7250
vue源码解读(二)
【Vue 源码解析】Vue实例挂载过程
源码位置:node_modules/vue/src/core/instance/index.js(ps:找不到可以在node_modules目录下搜索,因为懒惰后边就不写node_modules/vue这两级目录了)
CODER-V
2023/03/19
8340
【Vue 源码解析】Vue实例挂载过程
Vue 2.0源码分析-实例挂载的实现
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 这个方法的实现是和平台、构建方式都相关的。接下来我们重点分析带 compiler 版本的 mount 实现,因为抛开 webpack 的 vue-loader,我们在纯前端浏览器环境分析 Vue 的工作原理,有助于我们对原理理解的深入。
越陌度阡
2023/11/24
2960
面试官:Vue实例挂载的过程中发生了什么?
vue构建函数调用_init方法,但我们发现本文件中并没有此方法,但仔细可以看到文件下方定定义了很多初始化方法
@超人
2021/02/26
1.5K0
Vue2.6源码(2):$mount方法干了啥
当时受限于篇幅,并未分析$mount方法内的执行流程,需要告诉大家的是。$mount方法内部执行的过程依然非常复杂,难以在一篇文章中详述,所以本文依然只会分析$mount方法的主体流程,至于内部的各个分支逻辑,笔者将在后续的文章中一一进行解析。从宏观到微观,从抽象到具体,是Vue源码分析系列文章的分析方式。
杨艺韬
2022/09/27
4530
Vue源码学习和分析笔记
compiler 目录包含 Vue.js 所有编译相关的代码。它包括把模板解析成 AST 语法树,AST语法树优化,代码生成等功能。
Tiffany_c4df
2019/09/04
1.3K0
vue-生命周期 源码
生命周期的过程就是vue实例从创建到销毁的过程。在这个过程中提供了一些钩子函数用于让用户自定义一些方法。
用户3258338
2019/10/08
4510
浅析Vue初始化过程(基于Vue2.6)
要回答这个问题,我们现将视线放到Vue源码中package.json文件中,有这么两行代码:
杨艺韬
2022/09/27
5440
Vue——$mount【十二】
前面我们简单的了解了 vue 初始化时的一些大概的流程,这里我们详细的了解下具体的内容;
思索
2024/08/15
1130
前端二面vue面试题(边面边更)1
有五种,分别是 State、 Getter、Mutation 、Action、 Module
bb_xiaxia1998
2023/01/03
9640
Vue2.5源码阅读笔记02—虚拟DOM的创建与渲染
Vue是数据驱动的MVVM框架,视图是由数据驱动生成的,因此对视图的修改不是通过操作 DOM,而是通过修改数据,相比传统使用jQuery的前端开发,能够大大简化代码量,尤其在交互逻辑复杂的情况下,减少DOM操作,直接操作数据会让代码的逻辑变的非常清晰、利于维护。
CS逍遥剑仙
2018/09/11
1.8K0
Vue2.5源码阅读笔记02—虚拟DOM的创建与渲染
社招前端经典vue面试题汇总
创建store很简单,调用pinia中的defineStore函数即可,该函数接收两个参数:
bb_xiaxia1998
2022/12/07
1K0
2022前端经典vue面试题(持续更新中)
一个SPA应用的路由需要解决的问题是 页面跳转内容改变同时不刷新 ,同时路由还需要以插件形式存在,所以:
bb_xiaxia1998
2022/09/16
1K0
vue源码解析入口文件
为了加深对vue的理解,之前我们实现了一版mini-vue现在我们来看真正的vue源码来看下到底vue是如何实现的.
玖柒的小窝
2021/11/03
8640
Vue.js源码逐行代码注解src下core下instance
达达前端
2023/10/08
3390
腾讯前端一面常考vue面试题汇总2
vue构建函数调用_init方法,但我们发现本文件中并没有此方法,但仔细可以看到文件下方定定义了很多初始化方法
bb_xiaxia1998
2023/01/04
6720
你想要的——vue源码分析(1)
Vue.js是现在国内比较火的前端框架,希望通过接下来的一系列文章,能够帮助大家更好的了解Vue.js的实现原理。本次分析的版本是Vue.js2.5.16。(持续更新中。。。)
can4hou6joeng4
2023/11/30
1620
前端常见vue面试题合集
通过webpack的tree-shaking功能,可以将无用模块“剪辑”,仅打包需要的
bb_xiaxia1998
2022/11/09
7390
「源码级回答」大厂高频Vue面试题(中)
本篇是「源码级回答」大厂高频Vue面试题系列的第二篇,本篇也是选择了面试中经常会问到的一些经典面试题,从源码角度去分析。
前端森林
2020/05/21
9930
「源码级回答」大厂高频Vue面试题(中)
Vue响应式原理
Vue是数据驱动视图实现双向绑定的一种前端框架,采用的是非入侵性的响应式系统,不需要采用新的语法(扩展语法或者新的数据结构)实现对象(model)和视图(view)的自动更新,数据层(Model)仅仅是普通的Javascript对象,当Modle更新后view层自动完成更新,同理view层修改会导致model层数据更新。
伯爵
2020/05/23
8560
相关推荐
vue源码解读(二)
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档