霍春阳版
2023年08月30日
一、实现
1.1 unmout()
const unmount = vnode => {
if (vnode.type === Fragment) {
vnode.children.forEach(c => unmount(c));
return;
}
const parent = vnode.el.parentNode;
if (parent) {
parent.removeChild(vnode.el);
}
};
1.2 processFragment()
const processFragment = (n1, n2, container, anchor) => {
if (!n1) {
n2.children.forEach(c => patch(null, c, container, anchor));
} else {
patchChildren(n1, n2, container, anchor);
}
};
二、调试
import { watch } from './reactivity/watch';
import { effect } from './reactivity/effect';
import { computed } from './reactivity/computed';
import { patchProp } from './runtime-core/patchProp';
import { jobQueue, flushJob } from './reactivity/scheduler';
import { reactive, shallowReactive, readonly } from './reactivity/reactive';
import { createRenderer, Text, Comment, Fragment } from './runtime-core/renderer';
const renderOps = {
setText(el, text) {
el.nodeValue = text;
},
createText(text) {
return document.createTextNode(text);
},
createComment(comment) {
return document.createComment(comment);
},
createElement(tag) {
return document.createElement(tag);
},
setElementText(el, text) {
el.textContent = text;
},
insert(el, parent, anchor = null) {
parent.insertBefore(el, anchor);
}
};
const renderer = createRenderer({ ...renderOps, patchProp });
const data = reactive({ msg: 'Hello World' });
effect(() => {
const vnode = {
type: Fragment,
children: [
{
type: 'div',
shapeFlag: 9,
children: data.msg + 1
},
{
type: 'div',
shapeFlag: 9,
children: data.msg + 2
},
{
type: 'div',
shapeFlag: 9,
children: data.msg + 3
}
]
};
renderer.render(vnode, document.querySelector('#app'));
});
setTimeout(() => {
data.msg = 'Hello World 修改';
}, 3000);