面试官:vue实例挂载的过程

本文深入解析Vue.js实例的初始化过程,包括_$init_方法的调用,$set、$get、$delete、$watch等响应式属性的定义,以及事件方法$on、$off、$emit的实现。同时,详细介绍了组件的挂载流程,特别是$mount方法如何调用_moutComponent_进行页面渲染。此外,文章还探讨了_update_方法如何生成和更新虚拟DOM,确保组件的正确渲染。
摘要由CSDN通过智能技术生成
  • new Vue的时候调用会调用_init方法

    • 定义 $set$get 、$delete$watch 等方法
    • 定义 $on$off$emit$off等事件
    • 定义 _update$forceUpdate$destroy生命周期

      源码位置: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)
      }

  • 调用$mount进行页面的挂载

  • 挂载的时候主要是通过mountComponent方法

    源码位置:src\platforms\web\runtime\index.js

    // public mount method
    Vue.prototype.$mount = function (
      el?: string | Element,
      hydrating?: boolean
    ): Component {
      el = el && inBrowser ? query(el) : undefined
      // 渲染组件
      return mountComponent(this, el, hydrating)
    }

  • 定义updateComponent更新函数

  • 执行render生成虚拟DOM

  • _update将虚拟DOM生成真实DOM结构,并且渲染到页面中

    _update主要功能是调用patch,将vnode转换为真实DOM,并且更新到页面中

    源码位置:src\core\instance\lifecycle.js

    Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
        const vm: Component = this
        const prevEl = vm.$el
        const prevVnode = vm._vnode
        // 设置当前激活的作用域
        const restoreActiveInstance = setActiveInstance(vm)
        vm._vnode = vnode
        // Vue.prototype.__patch__ is injected in entry points
        // based on the rendering backend used.
        if (!prevVnode) {
          // initial render
          // 执行具体的挂载逻辑
          vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
        } else {
          // updates
          vm.$el = vm.__patch__(prevVnode, vnode)
        }
        restoreActiveInstance()
        // update __vue__ reference
        if (prevEl) {
          prevEl.__vue__ = null
        }
        if (vm.$el) {
          vm.$el.__vue__ = vm
        }
        // if parent is an HOC, update its $el as well
        if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
          vm.$parent.$el = vm.$el
        }
        // updated hook is called by the scheduler to ensure that children are
        // updated in a parent's updated hook.
      }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值