vue实例没有挂载到html上,vue 源码学习 - 实例挂载

前言

在学习vue源码之前需要先了解源码目录设计(了解各个模块的功能)丶Flow语法。

src

├── compiler # 把模板解析成 ast 语法树,ast 语法树优化,代码生成等功能。

├── core # 核心代码 Vue.js 的灵魂

├── platforms # 不同平台的支持 web 和 weex

├── server # 服务端渲染这部分代码是跑在服务端的 Node.js

├── sfc # .vue 文件解析

├── shared # 工具方法

复制代码

flow语法可以参照 v-model源码学习中提到的flow语法介绍,以及到官网了解更多。

vue 实例化

vue 本质上就是一个用 Function 实现的 Class,然后它的原型 prototype 以及它本身都扩展了一系列的方法和属性

vue 的定义

在 src/core/instance/index.js 中

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'

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)

}

initMixin(Vue)

stateMixin(Vue)

eventsMixin(Vue)

lifecycleMixin(Vue)

renderMixin(Vue)

export default Vue

复制代码

通过源码我们可以看到,它实际上就是一个构造函数。我们往后看这里有很多 xxxMixin 的函数调用,并把 Vue 当参数传入,它们的功能都是给 Vue 的 prototype 上扩展一些方法。

阶段

首先通过new Vue实例化,过程可以参考之前写的vue 生命周期梳理

vue 实例挂载的实现

Vue中是通过$mount实例方法去挂载vm,$mount方法再多个文件中都有定义,和平台,构建方式相关。 首先来看 src/platform/web/entry-runtime-with-compiler.js文件中

const mount = Vue.prototype.$mount

Vue.prototype.$mount = function (

el?: string | Element,

hydrating?: boolean

): Component {

el = el && query(el)

// A-> ..... 代表后面省略的代码从A-> 处接下去

}

复制代码

1.这段代码首先缓存了原型上的$mount 方法,再重新定义该方法

为了对比前后方法的差别,我们可以先看

compiler 版本的 $mount

a710d27ce4ada4e5fb52d82c33093d1f.png

2. $mount方法支持传入两个参数,第一个是el,它表示挂载的元素,可以是字符串,可以是DOM对象,会调用query方法转换成DOM对象,在浏览器环境下我们不需要传第二个参数,它是一个可选参数。

接下来继续看后面的代码

//

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

// A-> ..... 代表后面省略的代码从A-> 处接下去

复制代码

首先对 el 做了限制,Vue 不能挂载在 body、html 这样的根节点上。如果是其中一个则返回this。this就是vue实例本身00ffcf091ed972237d8a958add41bec5.png

定义option对象(new Vue中传入的数据)

//

if (!options.render) {

let template = options.template

if (template) {

// B-> ..... 代表后面省略的代码从B-> 处接下去

}else if(el){

// C-> ..... 代表后面省略的代码从C-> 处接下去

}

if (template) {

// D-> ..... 代表后面省略的代码从D-> 处接下去

}

return mount.call(this, el, hydrating)

}

复制代码判断有没有定义render方法,没有则会把el或者template字符串转换成render方法。在 Vue 2.0 版本中,所有 Vue 的组件的渲染最终都需要 render 方法

//

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

}

}

复制代码判断template 是否为字符串,取字符串的第一位判断是否是# 如果是#开头代表节点字符串,并调用idToTemplate方法如下

const idToTemplate = cached(id => {

const el = query(id)

return el && el.innerHTML

})

复制代码

接受一个参数,对这个参数进行query方法,前面提到query是将字符串转化成DOM,并且返回DOM的innerHTML

//

template = getOuterHTML(el)

复制代码

如果没有render和template的情况下,使用getOuterHTML方法重新定义template

function getOuterHTML (el: Element): string {

if (el.outerHTML) {

return el.outerHTML

} else {

const container = document.createElement('div')

container.appendChild(el.cloneNode(true))

return container.innerHTML

}

}

复制代码挂在DOM元素的HTML会被提取出来用作模板

be5ef99e5da3e9bcaadae7adb5fa9642.png

总结 : render函数优先级最高,template和el次之

模板类型

render : 类型function 接收一个 createElement 方法作为第一个参数用来创建 VNode

render: function (createElement) {

return createElement(

'h' + this.level, // 标签名称

this.$slots.default // 子元素数组

)

},

复制代码template:类型string 一个字符串模板作为 Vue 实例的标识使用。模板将会 替换 挂载的元素。

el:类型string | HTMLElement 提供一个在页面上已存在的 DOM 元素作为 Vue 实例的挂载目标。可以是 CSS 选择器,也可以是一个 HTMLElement 实例

runtime only 版本的$mount

Vue.prototype.$mount = function (

el?: string | Element,

hydrating?: boolean

): Component {

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

return mountComponent(this, el, hydrating)

}

复制代码

开始和compiler版本的$mount 实现相同,只不过多加了一个inBrowser判断是否在浏览器环境下。

$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

}

callHook(vm, 'beforeMount')

// A-> ..... 代表后面省略的代码从A-> 处接下去

}

复制代码mountComponent接收到Vue.prototype.$mount方法中vue实例对象,和el字符串(经过query处理已经转成DOM)

更新vm实例上的$el

判断vm上有无render模板,如果没有创建一个空的虚拟VNode

插入beforeMount钩子

//

let updateComponent

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

}else{

updateComponent = () => {

vm._update(vm._render(), hydrating)

}

}

vm._watcher = new Watcher(vm, updateComponent, noop)

// A-> ..... 代表后面省略的代码从A-> 处接下去

复制代码mountComponent 核心就是先调用vm._render方法先生成虚拟 Node 将 vm._update方法作为返回值赋值给updateComponent

实例化Watcher构造函数,将updateComponent作为回调函数,也就是说在实例化Watcher后最终调用vm._update 更新 DOM。

watcher的作用

实例化的过程后执行回调,将调用vm._update 更新 DOM。

vm 实例中的监测的数据发生变化的时候执行回调函数实现更新DOM

//

hydrating = false

if (vm.$vnode == null) {

vm._isMounted = true

callHook(vm, 'mounted')

}

return vm

复制代码

这里vm.$vnode的值是什么,文件定义在src/core/instance/render.js 中,这里只关注vm.$vnode所以贴出相关代码

export function renderMixin (Vue: Class) {

Vue.prototype._render = function (): VNode {

const vm: Component = this

const { render, _parentVnode } = vm.$options

vm.$vnode = _parentVnode

}

}

复制代码

renderMixin函数接收Vue实例参数,在vue原型上的内部_render方法需要返回一个VNode,并且通过结构赋值的方法取出实例中$options的属性和方法。

我们来看看vm.$options对象具体有些什么

82e845bb54990140256da6c70ad73a20.png

对象中有render函数,但是还未定义_parentVnode。可以知道vm.$vnode 表示 Vue 实例的父虚拟 Node,而且在mountComponent 函数中值还未定义。

由于未定义vm.$vnode值为undefined 所以vm.$vnode==null结果也为真

a1957f237ad6b9aa7ceab5d10a8ab879.png

我们也可以通过生命周期图来理解, VNode render 是发生在beforeUPdate 之后updated之前这个环节

流程 :(1) new Vue ==> (2) init ==> (3) $mount ==> (4) compile ==> (5) render ==> (6) vnode ==> (7) patch ==> (8) DOM

最后设置 vm._isMounted 为 true作为之后判断是否经历了mounted生命周期的条件

总结

判断挂载的节点不能挂载在 body、html 上。

模板优先级render>template>el 并且最终都会转换成render方法

知道mountComponent方法 做了什么,先是调用了vm._render 方法先生成虚拟 Node,然后实例化Watcher 执行它,并监听数据变化,实时更新。

设置vm._isMounted标志,作为判断依据

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值