let regular = /\{\{(.+?)}\}/g;
function compile(template, data) {
let childNodes = template.childNodes;
for (let i = 0; i < childNodes.length; i++) {
let type = childNodes[i].nodeType
if (type === 3) {
let textContent = childNodes[i].nodeValue
let text = textContent.replace(regular, (_, g) => {
let path = g.trim()
let value = valueBypath(data, path)
return value
})
childNodes[i].nodeValue = text
} else if (type === 1) {
compile(childNodes[i], data)
}
}
}
function valueBypath(obj, path) {
let paths = path.split(".")
let res = obj
let props
while (props = paths.shift()) {
res = res[props]
}
return res
}
class ssjVue {
constructor(options) {
this._data = options.data
this._el = options.el
this.$el = this._templateDom = document.querySelector(this._el)
this._parent = this._templateDom.parentNode;
this.render()
}
render() {
this.compiler();
}
compiler() {
let realHtomlDom = this._templateDom.cloneNode(true)
compile(realHtomlDom, this._data);
this.update(realHtomlDom)
}
update(real) {
this._parent.replaceChild(real,docunment,querySelector(`${this._el}`))
}
}
class Vnode {
constructor(tag, data, value, type) {
this.tag = tag && tag.toLowerCase();
this.data = data
this.value = value
this.type = type
this.children = []
}
appendChild(vnode) {
this.children.push(vnode)
}
}
function getVnode(node) {
let nodeType = node.nodeType
let _vnode = null
switch (nodeType) {
case 1:
let nodeName = node.nodeName
let attrs = node.attributes
let _attrObj = {}
for (let i = 0; i < attrs.length; i++) {
_attrObj[attrs[i].nodeName] = attrs[i].nodeValue
}
_vnode = new Vnode(nodeName, _attrObj, undefined, nodeType)
let childrenNodes = node.childNodes;
for (let i = 0; i < childrenNodes.length; i++) {
_vnode.appendChild(getVnode(childrenNodes[i]))
}
break;
case 3:
_vnode = new Vnode(undefined, undefined, node.nodeValue, nodeType)
break
}
return _vnode
}
function parseVnode(vnode) {
let realnode = vnode
console.log(realnode)
let realnodeType = realnode.type
console.log(realnodeType)
let _realnode = null
if (realnodeType === 1) {
let nodeName = realnode.tag
let attrs = realnode.data
let attrsObj = {}
for (let i = 0; i < attrs.length; i++) {
}
_realnode = document.createElement(nodeName)
let childrenNodes = realnode.children;
console.log(childrenNodes)
for (let i = 0; i < childrenNodes.length; i++) {
_realnode.appendChild(parseVnode(childrenNodes[i]))
}
} else if (realnodeType === 3) {
_realnode = document.createTextNode(vnode)
}
return _realnode
}
let app = new ssjVue({
el: '#root',
data: {
name: 'ssj',
age: 22,
love: 'playgame',
over: {
xixi: 1111
}
}
})