h函数的主要功能是根据传进来的函数返回一个vnode对象,之后便是patch方法将其挂载到页面
//index.js
import h from "./mysnabbdom/h"
let mynode = h("div", {}, [
h("p", {}, "ll"),
h("p", {}, "ll"),
h("p", {}, h("p", {}, "ll"))
])
console.log(mynode)
// 三种情况
// h("div", {}, [h("p", {}, "test"), h("p", {}, "test")])
// h("div", {}, h("p", {}, "test"))
// h("div", {}, "test")
//h.js
import vnode from "./vnode"
export default function (sel, data, c) {
//检查参数个数
if (arguments.length != 3) throw new Error("必须传入三个函数")
//判断第三个参数的类型
if (typeof c == "string" || typeof c == "number") {
return vnode(sel, data, undefined, c, undefined)
} else if (Array.isArray(c)) {
//遍历c,收集children
let children = []
for (let i = 0; i < c.length; i++) {
//检查c[i]是否满足是一个对象
if (!(typeof c[i] == "object" && c[i].hasOwnProperty("sel"))) {
throw new Error("传入的数组参数中有项不是h函数")
}
children.push(c[i])
}
//循环结束,children收集完毕,返回虚拟节点
return vnode(sel, data, children, undefined, undefined)
} else if (typeof c == "object" && c.hasOwnProperty("sel")) {
//传入的C是唯一children
let children = [c]
return vnode(sel, data, children, undefined, undefined)
} else {
throw new Error("传入的第三个参数值不对")
}
}
//vnode.js
export default function (sel, data, children, text, elm) {
return { sel, data, children, text, elm }
}