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使用内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。