手动敲敲代码,就很容易理解了,供参考
1、以下是VUE双向绑定的原理(简单版)
主要是监听和defineProperty实现简单的双向绑定
<html>
<head>
</head>
<body>
<div>
<input id="inputId"></input>
<span id="showId"></span>
</div>
<script>
var obj = {
name: '',
};
document.getElementById('inputId').addEventListener('keyup', function(event){
console.log('-----event-', event.target.value);
obj.name = event.target.value;
});
Object.defineProperty(obj, 'name', {
get() {
console.log('-------get---');
},
set(newVal) {
console.log('---------set---', newVal);
document.getElementById('inputId').value = newVal;
document.getElementById('showId').innerHTML = newVal;
}
});
</script>
</body>
</html>
2、以下是虚拟DOM 节点的创建
// 生成dom
function createDOM(target) {
const tag = target.tag || null;
const attr = target.attris || {};
const children = target.children || [];
if (!tag) {
return null;
}
let node = document.createElement(tag);
for (const key in attr) {
if (object.hasOwnProperty(key)) {
node.setAttribute(key, attr[key]);
}
}
children.forEach(child => {
node.appendChild(createDOM(child));
});
return node;
};
3、以下是更新DOM 节点(简单版,供参考)
// 更新虚拟dom
function updateNode(vNode, newVnode) {
const children = vNode.children || [];
const newChildren = newVnode.children || [];
children.forEach((childVNode, index) => {
let newChildVNode = newChildren[index]
if (childVNode.tag === newChildVNode.tag) {
updateNode(childVNode, newChildVNode);
} else {
replaceNode(childVNode, newChildVNode);
}
});
}
我不知道要多少个字才可以发布这篇文章,现在发一篇文章怎么这么难咯???唉!我就是想发一篇文章而已,没别的想法,不发广告,我y