Cosen95/blog

Vue源码探秘(实例挂载$mount)

Opened this issue · 0 comments

引言

本篇文章,我们来分析一下vm.$mount内部具体发生了什么。

实例挂载($mount)

我们知道$mount被定义在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);
};

其实不仅在这里有定义$mount方法,在src/platform/web/entry-runtime-with-compiler.jssrc/platform/weex/runtime/index.js都有定义。因为$mount方法的实现是和平台、构建方式都相关的。

在运行时(Runtime Only)版本的Vue中,调用的就是上面的这个$mount函数。而在完整版(Runtime + Compiler)的Vue中,$mount函数在src/platform/web/entry-runtime-with-compiler.js中被重写,这部分代码是我们这里要着重分析的。先看一下整体结构:

// src/platforms/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);

  // ...

  return mount.call(this, el, hydrating);
};

这里先拿到了Runtime Only版本的$mount方法,然后进行重写,最后又调用了Runtime Only版本的$mount方法。参数的类型检查表明el可以是字符串或DOM节点。接下来又调用了query方法:

// src/platforms/web/util/index.js
/**
 * Query an element selector if it's not an element already.
 */
export function query(el: string | Element): Element {
  if (typeof el === "string") {
    const selected = document.querySelector(el);
    if (!selected) {
      process.env.NODE_ENV !== "production" &&
        warn("Cannot find element: " + el);
      return document.createElement("div");
    }
    return selected;
  } else {
    return el;
  }
}

query函数的逻辑比较简单: 如果el是一个字符串,就调用querySelector获取节点并返回;如果节点不存在就抛出警告并创建一个div节点。如果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;
}

这里去检查el是不是根节点(html)、(body),如果是就抛出警告并停止挂载。

Vue是不能挂载在bodyhtml这样的根节点上的,因为挂载实际上就是把el节点替换为组件的模版。

继续往下看:

const options = this.$options;
// resolve template/el and convert to render function
if (!options.render) {
  let template = options.template;
  if (template) {
    // [1] ...
  } else if (el) {
    template = getOuterHTML(el);
  }
  // [2] ...
}

首先判断render函数是否存在,如果未定义则需做进一步处理。

Vue2.0 开始,所有组件的渲染都需要用到render函数,无论是我们上一节的例子还是使用.vue文件编写。

进入if判断后先拿到options.template,如果template存在就执行[1]处的代码:

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;
}

先判断template是否是字符串,如果是字符串而且是id选择器,通过idToTemplate方法拿到相应节点,如果拿不到会抛出警告。如果是字符串但不是选择器,不作处理。

如果template是一个节点,那么获取它的innerHTML

如果template既不是字符串也不是一个节点,那么抛出警告并结束挂载。

如果template不存在,接着判断el是否存在,存在则执行template = getOuterHTML(el)。来看下getOuterHTML函数:

// src/platforms/web/entry-runtime-with-compiler.js
/**
 * Get outerHTML of elements, taking care
 * of SVG elements in IE as well.
 */
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;
  }
}

这里判断el.outerHTML是否存在,有就返回outerHTML

IE9-11SVG 标签元素是没有 innerHTMLouterHTML 这两个属性的。

else中就是对以上情况的兼容处理: 在el的外面包装了一层div,然后获取该divinnerHTML

这样无论是 template 还是 el ,都被转为了字符串模板,然后执行[2]处的代码:

if (template) {
  /* istanbul ignore if */
  if (process.env.NODE_ENV !== "production" && config.performance && mark) {
    mark("compile");
  }

  const { render, staticRenderFns } = compileToFunctions(
    template,
    {
      outputSourceRange: process.env.NODE_ENV !== "production",
      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");
  }
}

这里先判断template是否存在(template可能为空字符串)。可以清楚的看到进入if语句内,里面有两个相同的if语句,这与我们之前介绍_init函数时遇到的一样,都是用于性能追踪。

中间这段代码调用了compileToFunctions函数,返回的render函数将其挂载到options.render上。
最后执行了:

return mount.call(this, el, hydrating);

这里是调用之前缓存的在src/platforms/web/runtime/index.js中定义的$mount函数:

// 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);
};

这里的 $mount 又把 el 从字符串转换成了节点然后传给了 mountComponent 函数。和上面一样,这里把 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");

  // ...
}

先将el保存到vm.$el上,然后判断前面的template是否被正确的转换成了render函数。如果转换失败,将createEmptyVNode作为render函数。createEmptyVNode函数会创建一个空的VNode对象。

在非生产环境下(一般是开发版本下),如果编写了template或者el的同时又使用了Runtime Only版本的Vue,导致在$mount中不能编译成render函数,则会抛出警告;另外如果既没有template也没有render函数也会抛出警告。

接下来调用的callHook函数是生命周期相关。继续往下看:

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);
  };
}

if语句里面是再熟悉不过的性能追踪,我们直接跳过,看else部分。

这里面定义了一个updateComponent函数,涉及到两个函数:

  • _render: 调用 vm.$options.render 函数并返回生成的虚拟节点(VNode
  • _update: 将 VNode 渲染成真实DOM

这里我只是大概说明一下它的作用,具体会在后面章节中展开。

接着往下看:

// 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 && !vm._isDestroyed) {
        callHook(vm, "beforeUpdate");
      }
    }
  },
  true /* isRenderWatcher */
);
hydrating = false;

这里创建了一个 Watcher 实例,显然是与响应式数据相关的。这里的 Watcher 也仅做了解,在后面的章节会具体分析。

Watcher 会解析表达式,收集依赖关系,并且在表达式的值发生改变时触发回调。Watcher 在这里主要有两个作用: 一个是初始化的时候会执行回调函数;另一个是当 vm 实例中监测的数据发生变化的时候执行回调函数,而回调函数就是传入的 updateComponent 函数。

回到 mountComponent 函数,还剩最后一段代码:

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

函数最后判断为根节点的时候设置 vm._isMountedtrue, 表示这个实例已经挂载了,同时执行 mounted 钩子函数。

这里注意 vm.$vnode 表示 Vue 实例的父虚拟 Node,所以它为 Null 则表示当前是根 Vue 的实例。

总结

这一节我们分析了 $mount 函数的大体执行流程,下一篇文章我将介绍 $mount 函数中_render 函数的实现。