vue中this.$createElement方法的使用

2022-07-29,,

vue this.$createelement方法

element ui中的slider的marks属性中使用到this.$createelement方法设置标记样式:

上面虽然只用到两个参数,实际上,此方法有三个参数:

①第一个参数为标签,即创建的节点元素的标签是什么

②第二个参数是属性配置,如class、style等

③第三个参数是节点元素的内容

this.$createelement方法的写法

const h = this.$createelement;
this.$info({
     title: 'this is a notification message',
     content: h('div', {}, [
         h('p', 'some messages...some messages...'),
         h('p', 'some messages...some messages...'),
     ]),
     onok() {},
});

生成的对话框如下:

使用第二个参数进行属性配置,例如以下代码:

h('div', { class: 'test' }, [
  h('p', 'some messages...some messages...'),
  h('p', 'some messages...some messages...')
])

生成的是:

可以看出,dom元素上多了class属性

再试试以下代码:

h('div', 
  {
    style: {
      color: 'green'
    }
  }, [
    h('p', 'some messages...some messages...'),
    h('p', 'some messages...some messages...')
])

生成的对话框的字体就会变成绿色:

关于createelement使用实例

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

《vue中this.$createElement方法的使用.doc》

下载本文的Word格式文档,以方便收藏与打印。