广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >Vue中createElement使用实例详解
  • 455
分享到

Vue中createElement使用实例详解

vuecreateElement使用vuecreateElement 2022-11-13 19:11:21 455人浏览 安东尼
摘要

目录一:参数说明二:使用示例三:源码解读Vue 提供了createElement 来创建虚拟dom,方便我们来函数化的方式来定义复杂的组件结构。在组件定义的时候,通常render函数

Vue 提供了createElement 来创建虚拟dom,方便我们来函数化的方式来定义复杂的组件结构。在组件定义的时候,通常render函数的参数里都会带上该函数的引用。方便用户调用。

一:参数说明

createElement 默认暴露给用户传递3个参数,参考文档代码介绍:

// @returns {Vnode}
createElement(
  // {String | Object | Function}
  // 一个 html 标签名、组件选项对象,或者
  // resolve 了上述任何一种的一个 async 函数。必填项。
  'div',

  // {Object}
  // 一个与模板中属性对应的数据对象。可选。
  {
    // (详情见下一节)
  },

  // {String | Array}
  // 子级虚拟节点 (VNodes),由 `createElement()` 构建而成,
  // 也可以使用字符串来生成“文本虚拟节点”。可选。
  [
    '先写一些文字',
    createElement('h1', '一则头条'),
    createElement(MyComponent, {
      props: {
        someProp: 'foobar'
      }
    })
  ]
)

二:使用示例

//创建一个div节点
createElement("div", {
	 return createElement("div", {
        domProps: {
          innerHTML: "hello !"
        }
      })
})
// 按照组件名来返回一个虚拟dom
createElement("component-name", {
   props: {
      name: "hello"
  }
})

//  设置子对象
return createElement("div", {
     class: "box"
}, [
   createElement("span", {
     domProps: {
           innerHTML: 'bob !'
     }
   })
 ])

三:源码解读

createElement 最终是通过调用new VNode 来创建虚拟dom,函数在调用new VNode之前处理了很多限制的情况,比如:data不能是响应式数据,tag是否为空等等,详见下面代码中的中文注释

function _createElement (
    context,
    tag,
    data,
    children,
    nORMalizationType
  ) {
    if (isDef(data) && isDef((data).__ob__)) { //检测是否是响应式数据
      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)) { //检测data中是否有is属性,是的话tag替换为is指向的内容,处理动态组件
      tag = data.is;
    }
    if (!tag) { // tag如果为空,创建空虚拟节点
      // in case of component :is set to falsy value
      return createEmptyVNode()
    }
    // warn against non-primitive key
    if (isDef(data) && isDef(data.key) && !isPrimitive(data.key) // data 中的key如果定义了必须是数字或者字符串
    ) {
      {
        warn(
          'Avoid using non-primitive value as key, ' +
          'use string/number value instead.',
          context
        );
      }
    }
    // support single function children as default scoped slot
    if (Array.isArray(children) &&
      typeof children[0] === 'function'
    ) {
      data = data || {};
      data.scopedSlots = { default: children[0] };
      children.length = 0;
    }
    // 标准化处理children的两种模式
    if (normalizationType === ALWAYS_NORMALIZE) {
      children = normalizeChildren(children);
    } else if (normalizationType === SIMPLE_NORMALIZE) {
      children = simpleNormalizeChildren(children);
    }
    var vnode, ns;
    if (typeof tag === 'string') {
      var Ctor;
      ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag);
      if (config.isReservedTag(tag)) { // 判读是否是标准的html 标签
        // platform built-in elements
        vnode = new VNode(
          config.parsePlatformTagName(tag), data, children,
          undefined, undefined, context
        );
      } else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {// 如果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);
    }
    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()
    }
  }

如下是VNode构造函数,包含了一个虚拟dom应该有的所有属性,虚拟dom是现代框架比较大的一个特色,不仅提高了dom渲染的效率,而且为跨平台提供了很好的标准。

var VNode = function VNode (
    tag,
    data,
    children,
    text,
    elm,
    context,
    componentOptions,
    asyncFactory
  ) {
    this.tag = tag;
    this.data = data;
    this.children = children;
    this.text = text;
    this.elm = elm;
    this.ns = undefined;
    this.context = context;
    this.fnContext = undefined;
    this.fnOptions = undefined;
    this.fnScopeId = undefined;
    this.key = data && data.key;
    this.componentOptions = componentOptions;
    this.componentInstance = undefined;
    this.parent = undefined;
    this.raw = false;
    this.isStatic = false;
    this.isRootInsert = true;
    this.isComment = false;
    this.isCloned = false;
    this.isOnce = false;
    this.asyncFactory = asyncFactory;
    this.asyncMeta = undefined;
    this.isAsyncPlaceholder = false;
  };

到此这篇关于Vue 中 createElement 使用详解的文章就介绍到这了,更多相关vue createElement使用内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Vue中createElement使用实例详解

本文链接: https://www.lsjlt.com/news/170333.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作