亲宝软件园·资讯

展开

Vue虚拟dom

yyds2026 人气:0

先来看生成虚拟dom的入口文件:

 ...
  import { parse } from './parser/index'
  import { optimize } from './optimizer'
  import { generate } from './codegen/index'
  ...
   const ast = parse(template.trim(), options)
  if (options.optimize !== false) {
    optimize(ast, options)
  }
  const code = generate(ast, options)
  ...

我们看到了AST经过三轮加工,最终脱胎换骨成为render function code。那么我们这一章就来讲AST的第三次试炼。入口文件./codegen/index

export function generate (
ast: ASTElement | void,
options: CompilerOptions
): CodegenResult {
const state = new CodegenState(options)
const code = ast ? genElement(ast, state) : '_c("div")'
return {
  render: `with(this){return $[code]}`,
  staticRenderFns: state.staticRenderFns
}
}

我们来看generate函数内部构造,返回render是一个with(this){return $[code]}包起来的一串东西,staticRenderFns是在编译过程中会把那些不会变的静态节点打上标记,设置为true,然后在渲染阶段单独渲染
那么genElement函数的作用是什么呢?

export function genElement (el: ASTElement, state: CodegenState): string {
  if (el.staticRoot && !el.staticProcessed) {
    return genStatic(el, state)
  } else if (el.once && !el.onceProcessed) {
    return genOnce(el, state)
  } else if (el.for && !el.forProcessed) {
    return genFor(el, state)
  } else if (el.if && !el.ifProcessed) {
    return genIf(el, state)
  } else if (el.tag === 'template' && !el.slotTarget) {
    return genChildren(el, state) || 'void 0'
  } else if (el.tag === 'slot') {
    return genSlot(el, state)
  } else {
    // component or element
    let code
    if (el.component) {
      code = genComponent(el.component, el, state)
    } else {
      const data = el.plain ? undefined : genData(el, state)

      const children = el.inlineTemplate ? null : genChildren(el, state, true)
      code = `_c('${el.tag}'${        data ? `,${data}` : '' // data      }${        children ? `,${children}` : '' // children      })`
    }
    // module transforms
    for (let i = 0; i < state.transforms.length; i++) {
      code = state.transforms[i](el, code)
    }
    return code
  }
}

我们可以看到有无限个if else在嵌套,而且onceforiftag就是Vue本身的屠特殊标签,并且最后有return code 那么就是拼接字符串
那么我们来看一看生成的with(this){return $[code]}长啥样:

<div id="app">
  <ul>
    <li v-for="item in items">
      itemid:{{item.id}}
    </li>
  </ul>
</div>

经过compile之后转化成:

with(this){
  return 
     _c('div',{
         attrs:{"id":"app"}
     },
     [_c('ul',_l((items),function(item){
       return _c('li',
                 [_v("\n      itemid:"+_s(item.id)+"\n    ")]
       )}
      )
     )]
   )}

到这里我们就把tamplate三次锤炼讲完了,那么render function code 有了,那真正的渲染函数在哪呢?进一步来揭晓:

return {
    ast, //AST模型
    render: code.render, //render函数字符串
    staticRenderFns: code.staticRenderFns //静态节点render函数字符串
  }

我们暴露出去一个astrenderstaticRenderFns分别为AST模型render函数字符串静态的render函数字符串,那么我们的render函数在那里呢?
我们知道在Vue初始化的时候initRender:

  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
  // normalization is always applied for the public version, used in
  // user-written render functions.
  vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)

该方法向vue上挂载了两个方法,一个服务于用户手写的render函数,一个则用于template模板。

export function renderMixin (Vue: Class<Component>) {
  // install runtime convenience helpers
  installRenderHelpers(Vue.prototype)

  Vue.prototype.$nextTick = function (fn: Function) {
    return nextTick(fn, this)
  }

  Vue.prototype._render = function (): VNode {
    const vm: Component = this
    const { render, _parentVnode } = vm.$options

    // reset _rendered flag on slots for duplicate slot check
    if (process.env.NODE_ENV !== 'production') {
      for (const key in vm.$slots) {
        // $flow-disable-line
        vm.$slots[key]._rendered = false
      }
    }

    if (_parentVnode) {
      vm.$scopedSlots = _parentVnode.data.scopedSlots || emptyObject
    }

    // set parent vnode. this allows render functions to have access
    // to the data on the placeholder node.
    vm.$vnode = _parentVnode
    // render self
    let vnode
    try {
      vnode = render.call(vm._renderProxy, vm.$createElement)
    } catch (e) {
      handleError(e, vm, `render`)
      // return error render result,
      // or previous vnode to prevent render error causing blank component
      /* istanbul ignore else */
      if (process.env.NODE_ENV !== 'production') {
        if (vm.$options.renderError) {
          try {
            vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
          } catch (e) {
            handleError(e, vm, `renderError`)
            vnode = vm._vnode
          }
        } else {
          vnode = vm._vnode
        }
      } else {
        vnode = vm._vnode
      }
    }
    // return empty vnode in case the render function errored out
    if (!(vnode instanceof VNode)) {
      if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
        warn(
          'Multiple root nodes returned from render function. Render function ' +
          'should return a single root node.',
          vm
        )
      }
      vnode = createEmptyVNode()
    }
    // set parent
    vnode.parent = _parentVnode
    return vnode
  }
}

向vue原型上挂载了_render方法,该方法在mount的过程中会被调用生成一个vnode实例用于update对比生成一个新的dom对象并对原dom节点进行替换,该方法将会拿到option上定义render方法:

new Vue({
    el:"#app",
    render(createElement){
        return createElement("div",{
            attr:{
                id:"app"
            }
        },this.message)
    },
    data(){
        return {
            message:"hello"
        }
    }
})

一种则是使用的template方式,但是该方法最终在mount的过程中通过调用compileToFunctions会被转化render函数,也就是说,最终供_render方法使用的实际上就是我们自定义的render函数,在初始化render中会代理Vue实例vm._renderProxy,其实就是vue,那么vm.$createElement就是添加在Vue原型上的一个方法(initRender阶段),所以就是createElement方法

/** * 创建vnode节点, 本质上是调_createElement方法, 这里做一层封装, 来兼容更多情况 */
export function createElement (
  context: Component,
  tag: any,
  data: any,
  children: any,
  normalizationType: any,
  alwaysNormalize: boolean
): VNode | Array<VNode> {
  if (Array.isArray(data) || isPrimitive(data)) {
    normalizationType = children
    children = data
    data = undefined
  }
  // 根据normalizationType的不同, 后续处理children的方式也不同, 详见core/vdom/helpers/normalzie-children.js
  if (isTrue(alwaysNormalize)) {
    normalizationType = ALWAYS_NORMALIZE
  }
  return _createElement(context, tag, data, children, normalizationType)
}


export function _createElement (
  context: Component,
  tag?: string | Class<Component> | Function | Object,
  data?: VNodeData,
  children?: any,
  normalizationType?: number
): VNode | Array<VNode> {
  // 如果节点的data已经是响应式, 即已有__ob__属性, 直接返回空节点并发出警告
  if (isDef(data) && isDef((data: any).__ob__)) {
    process.env.NODE_ENV !== 'production' && warn(
      'Avoid using observed data object as vnode data:' + ` ${JSON.stringify(data)}\n` +
      'Always create fresh vnode data objects in each render!',
      context
    )
    return createEmptyVNode()
  }
  // 处理动态组件
  // object syntax in v-bind
  if (isDef(data) && isDef(data.is)) {
    tag = data.is
  }
  // 没有tag字段的组件直接返回一个空节点
  if (!tag) {
    // in case of component :is set to falsy value
    return createEmptyVNode()
  }
  // warn against non-primitive key
  // 检查key是否是string or number
  if (process.env.NODE_ENV !== 'production' &&
    isDef(data) && isDef(data.key) && !isPrimitive(data.key)
  ) {
    if (!__WEEX__ || !('@binding' in data.key)) {
      warn(
        'Avoid using non-primitive value as key, ' +
        'use string/number value instead.',
        context
      )
    }
  }
  // support single function children as default scoped slot
  // 对于children数组的两种处理方式, 详见helper/normalize-children.js
  if (Array.isArray(children) &&
    typeof children[0] === 'function'
  ) {
    data = data || {}
    data.scopedSlots = { default: children[0] }
    children.length = 0
  }
  if (normalizationType === ALWAYS_NORMALIZE) {
    children = normalizeChildren(children)
  } else if (normalizationType === SIMPLE_NORMALIZE) {
    children = simpleNormalizeChildren(children)
  }
  let vnode, ns
  /**   * 先对tag进行判断 如果是 string ,接着判断是否是dom内置的节点,如果是则直接创建一个普通 VNode   * 如果是为已注册的组件名,则通过 createComponent 创建一个组件类型的 VNode   * 否则创建一个未知的标签的 VNode   *    * 如果tag是Component类型, 通过createComponent创建一个节点   */
  if (typeof tag === 'string') {
    let Ctor
    ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)
    if (config.isReservedTag(tag)) {
      // platform built-in elements
      vnode = new VNode(
        config.parsePlatformTagName(tag), data, children,
        undefined, undefined, context
      )
    } else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
      // component
      vnode = createComponent(Ctor, data, context, children, tag)
    } else {
      // unknown or unlisted namespaced elements
      // check at runtime because it may get assigned a namespace when its
      // parent normalizes children
      vnode = new VNode(
        tag, data, children,
        undefined, undefined, context
      )
    }
  } else {
    // direct component options / constructor
    vnode = createComponent(tag, data, context, children)
  }
  // 对vnode进行标准化处理, 保证每次都返回一个标准格式的vnode
  if (Array.isArray(vnode)) {
    return vnode
  } else if (isDef(vnode)) {
    if (isDef(ns)) applyNS(vnode, ns)
    if (isDef(data)) registerDeepBindings(data)
    return vnode
  } else {
    return createEmptyVNode()
  }
}

// 对每个children节点应用命名空间
function applyNS (vnode, ns, force) {
  vnode.ns = ns
  if (vnode.tag === 'foreignObject') {
    // use default namespace inside foreignObject
    ns = undefined
    force = true
  }
  if (isDef(vnode.children)) {
    for (let i = 0, l = vnode.children.length; i < l; i++) {
      const child = vnode.children[i]
      if (isDef(child.tag) && (
        isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) {
        applyNS(child, ns, force)
      }
    }
  }
}

// ref #5318
// necessary to ensure parent re-render when deep bindings like :style and
// :class are used on slot nodes
// 对于style和class进行深度递归绑定
function registerDeepBindings (data) {
  if (isObject(data.style)) {
    traverse(data.style)
  }
  if (isObject(data.class)) {
    traverse(data.class)
  }
}

其中在判断ALWAYS_NORMALIZEnormalizationType时候,用户手写的ALWAYS_NORMALIZE一直是true,所以就会调用normalizeChildren(children)

export function simpleNormalizeChildren (children: any) {
  for (let i = 0; i < children.length; i++) {
    if (Array.isArray(children[i])) {
      return Array.prototype.concat.apply([], children)
    }
  }
  return children
}

export function normalizeChildren (children: any): ?Array<VNode> {
  return isPrimitive(children)
    ? [createTextVNode(children)]
    : Array.isArray(children)
      ? normalizeArrayChildren(children)
      : undefined
}

加载全部内容

相关教程
猜你喜欢
用户评论