-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomponent.html
467 lines (423 loc) · 14.8 KB
/
component.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/@vue/[email protected]/dist/reactivity.global.js"></script>
</head>
<body>
<div id="app"></div>
</body>
<script>
// 组件
const vnode = {
type: 'h1',
props: {
'class': 'box'
},
children: 'hello'
}
let currentInstance = null
const setCurrentInstance = () => {
}
function createRenderer() {
const hasPropsChange = (prevProps, nextProps) => { // 判断父组件前后为子组件所传递的props是否发生了变化
const nextKeys = Object.keys(nextProps)
if (nextKeys.length !== Object.keys(prevProps).length) { // 新旧props数量不等情形
return true
}
for (let i = 0; i < nextKeys.length; i++) {
const key = nextKeys[i]
if (nextProps[key] !== prevProps[key]) { //
return true
}
}
return false
}
const patchComponent = (n1, n2, anchor) => { // 组件更新
const instance = (n2.component = n1.component)
const {props} = instance
if (hasPropsChange(n1.props, n2.props)) {
const [nextProps] = resolveProps(n2.type.props, n2.props) // 获取新的props数据
for (const key in nextProps) { // 更新已有的props
props[key] = nextProps[key]
}
for (const key in props) { // 删除不存在的props
if (!(key in nextProps)) {
delete props[key]
}
}
}
}
const resolveProps = (options, propsData) => { // 解析props数据
const props = {}
const attrs = {}
for (const key in propsData) {
if (key in options || key.startsWith('on')) { // 以on开头都添加到props中去
props[key] = propsData[key]
} else {
attrs[key] = propsData[key]
}
}
return [props, attrs]
}
// 进行组件的初始渲染
const mountComponent = (vnode, container, anchor) => {
const componentOptions = vnode.type
const {render, data, setup, props: propsOption, beforeCreate, created, beforeMount, mounted, beforeUpdate, updated} = componentOptions
beforeCreate && beforeCreate()
const state = data ? reactive(data()) : null
const [props, attrs] = resolveProps(propsOption, vnode.props)
const slots = vnode.children || {}
const instance = {
state,
isMounted: false,
subTree: null,
props: shallowReactive(props),
slots
}
const emit = (event, ...payload) => {
const eventName = `on${event[0].toUpperCase() + event.slice(1)}`
const handler = instance.props[eventName]
if (handler) {
handler(...payload)
} else {
console.error('事件不存在');
}
}
// setup相关内容
const setupContext = {attrs, emit, slots}
const setupResult = setup(shallowReadonly(instance.props), setupContext)
const setupState = null
if (typeof setupResult === 'function') {
if (render) {
console.error('setup函数返回渲染函数, render选项将被忽略');
}
render = setupResult
} else {
setupState = setupResult
}
vnode.component = instance
// 创建instance的代理对象,当在渲染函数或者生命周期钩子中读取this属性值时被该对象拦截,读取或设置属性值时先从组件自身状态中进行,如果组件本身没有对应数据,再从props中数据中进行,还包括methods,computed,甚至是setupState等
const renderContext = new Proxy(instance, {
get (target, key, receiver) {
const {state, props, slots} = target
if (key === '$slots') {
return slots
}
if (state && key in state) {
return state[key]
} else if (key in props) {
return props[key]
} else if (setupState && key in setupState) { // 渲染上下文需要增加对setupState的支持
return setupState[key]
} else {
console.error('该属性不存在');
}
},
set (target, key, value, receiver) {
const {state, props} = target
if (state && key in state) {
state[key] = value
} else if (key in props) {
props[key] = value
} else if (setupState && key in setupState) { // 渲染上下文需要增加对setupState的支持
setupState[key] = value
} else {
console.error('该属性不存在');
}
}
})
created && created.call(state)
effect(() => {
const subTree = render.call(state, state)
if (!instance.isMounted) {
beforeMount && beforeMount.call(state)
patch(null, subTree, container, anchor) // 初次进行挂载
instance.isMounted = true
mounted && mounted.call(state)
} else {
beforeUpdate && beforeUpdate.call(state)
patch(instance.subTree, subTree, container, anchor)
updated && updated.call(state)
}
instance.subTree = subTree
}, {
scheduler: queueJob
})
}
const patchKeyedChildren = (n1, n2, container) => {
const oldChildren = n1.children
const newChildren = n2.children
// 更新所有前置节点
let j = 0
let oldVNode = oldChildren[j]
let newVNode = newChildren[j]
while (oldVNode.key === newVNode.key) {
// 使用while循环寻找所有相同前置节点,并进行打补丁
patch(oldVNode, newVNode, container)
j++
oldVNode = oldChildren[j]
newVNode = newChildren[j]
}
// 更新所有后置节点
let oldEnd = oldChildren.length - 1
let newEnd = newChildren.length - 1
oldVNode = oldChildren[oldEnd]
newVNode = newChildren[newEnd]
while (oldVNode.key === newVNode.key) {
patch(oldVNode, newVNode, container)
oldEnd--
newEnd--
oldVNode = oldChildren[oldEnd]
newVNode = newChildren[newEnd]
}
if (j > oldEnd && j <= newEnd) {
// 满足如下条件,说明从j-newEnd之间的节点应作为新节点进行插入
const anchorIndex = newEnd + 1 // 锚点索引
const anchor = anchorIndex < newChildren.length ? newChildren[anchorIndex].el : null
while (j <= newEnd) {
// 调用patch逐个挂载新节点
patch(null, newChildren[j++], container, anchor)
}
} else if (j > newEnd && j <= oldEnd) {
// 满足如下条件,说明从j-oldEnd之间的节点应该被进行卸载
while (j <= oldEnd) {
unmount(oldChildren[j++])
}
} else {
// 增加else分支来处理非理想情况
const count = newEnd - j + 1
const source = new Array(count)
source.fill(-1)
const oldStart = j
const newStart = j
// 两层循环嵌套有时会有性能问题
// for (let i = oldStart; i <= oldEnd; i++) {
// const oldVNode = newChildren[i]
// for (let k = newStart; k <= newEnd; k++) {
// const newVNode = newChildren[k]
// if (oldVNode.key === newVNode.key) {
// patch(oldVNode, newVNode, container)
// source[k - newStart] = i
// }
// }
// }
const moved = false
const pos = 0
const keyIndex = {}
for (let i = newStart; i < newEnd; i++) {
keyIndex[newChildren[i].key] = i
}
let patched = 0
for (let i = oldStart; i < oldEnd; i++) {
oldVNode = oldChildren[i]
if (patch < count) {
const k = keyIndex[oldVNode.key]
if (typeof k !== 'undefined') {
newVNode = newChildren[k]
patch(oldVNode, newVNode, container)
source[k - newStart] = i
patched++
if (k < pos) {
moved = true
} else {
pos = k
}
} else {
unmount(oldVNode)
}
} else {
unmount(oldVNode)
}
}
if (moved) {
// ......
}
}
}
const patchChildren = (n1, n2, container) => { // 更新children
if (typeof n2.children === 'string') { // 新子节点是文本子节点
if (Array.isArray(n1.children)) {
n1.children.forEach(c => unmount(c)) // 逐个卸载旧子节点
}
setElementText(container, n2.children)
} else if (Array.isArray(n2.children)) { // 新子节点是一组子节点
if (Array.isArray(n1.children)) {
patchKeyedChildren(n1, n2, container)
} else {
// 旧节点要么是文本子节点,要么不存在
setElementText(container, '') // 先清空容器
n2.children.forEach(c => patch(null, c, container)) // 再将新的一组子节点逐个进行挂载
}
} else {
// 新子节点不存在
if (Array.isArray(n1.children)) {
n1.children.forEach(c => unmount(c)) // 旧子节点是一组,逐个进行卸载
} else if (typeof n1.children === 'string') {
setElementText(container, '') // 旧子节点是文本,直接进行清空即可
}
}
}
const patchElement = (n1, n2) => { // 打补丁(更新)
const el = n2.el = n1.el
const oldProps = n1.props
const newProps = n2.props
// 第一步:更新这个props
for (const key in newProps) {
if (newProps[key] !== oldProps[key]) {
patchProps(el, key, oldProps[key], newProps[key])
}
}
for (const key in oldProps) {
if (!(key in newProps)) {
patchProps(el, key, oldProps[key], null)
}
}
// 第二步:更新children
patchChildren(n1, n2, el)
}
const shouldSetAsProps = (el, key) => {
// 判断dom properties是否是只读,如果是只读通过setAttribute来设置属性
if (key === 'form' && el.tagName === 'INPUT') {
return false
}
return key in el
}
const mountElement = (vnode, container, anchor) => { // 第一次挂载过程
const el = vnode.el = createElement(vnode.type) // 让vnode.el引用真实dom元素
if (vnode.props) { // 处理vnode中的props
for (const key in vnode.props) {
// el.setAttribute(key, vnode.props[key]) // 直接设置有缺陷
patchProps(el, key, null, vnode.props[key])
}
}
if (typeof vnode.children === 'string') { // 处理vnode中的children
setElementText(el, vnode.children)
} else if (Array.isArray(vnode.children)) {
vnode.children.forEach(child => {
patch(null, child, el)
})
}
insert(el, container, anchor)
}
const patch = (n1, n2, container, anchor) => {
if (n1 && n1.type !== n2.type) { //如果新旧node的type不同,直接卸载旧的node
unmount(n1)
n1 = null
}
const { type } = n2
if (type === 'string') { // 普通标签元素
if (!n1) { // 挂载
mountElement(n2, container, anchor)
} else { // 打补丁(更新)
patchElement(n1, n2)
}
} else if (type === Text) { // 文本节点
if (!n1) {
const el = n2.el = createText(n2.children)
insert(el, container)
} else {
const el = n2.el = n1.el
if (n2.children !== n1.children) {
setText(el, n2.children)
}
}
} else if (type === Fragment) { // 片段
if (!n1) {
n2.children.forEach(c => patch(null, c, container))
} else {
patchChildren(n1, n2, container)
}
} else if (type === 'object') { // 组件
if (!n1) {
mountComponent(n2, container, anchor) // 挂载组件
} else {
patchComponent(n1, n2, anchor) // 更新组件
}
}
}
const unmount = (vnode) => { // 卸载操作
if (vnode.type === Fragment) {
vnode.children.forEach(c => unmount(c))
return
}
const parent = vnode.el.parent
if (parent) parent.removeChild(vnode.el)
}
const render = (vnode, container) => {
if (vnode) {
patch(container._vnode, vnode, container) // 挂载或更新
} else {
if (container._vnode) {
// container.innerHTML = '' // 卸载,这样的卸载操作有缺陷
unmount(container._vnode)
}
}
container._vnode = vnode
}
return {
render
}
}
const renderer = createRenderer(
{
createElement(tag) {
return document.createElement(tag)
},
createText(text) {
return document.createTextNode(text)
},
setText(el, text) {
el.nodeValue = text
},
setElementText(el, text) {
el.textContent = text
},
insert(el, parent, anchor = null) {
parent.insertBefore(el, anchor)
},
patchProps(el, key, preValue, nextValue) { // 用来对dom对象上的props进行更新操作
if (/^on/.test(key)) { // 对事件进行处理
let invokers = el._vei || (el._vei = {})
const invoker = invokers[key]
const name = key.slice(2).toLowerCase()
if (nextValue) {
if (!invoker) { // 添加绑定
invoker = el._vei[key] = (e) => { // 伪造事件处理函数
if (e.timestamp < invoker.attached) return;
if (Array.isArray(invoker.value)) { // 判断同一个事件绑定多个处理函数
invoker.value.forEach(fn => fn(e))
} else {
invoker.value(e)
}
}
invoker.value = nextValue
invoker.attached = performance.now()
el.addEventListener(name, invoker)
} else { // 更新,直接更新invoker的value值即可
invoker.value = nextValue
}
} else if (invoker) { // 卸载
el.removeEventListener(name, invoker)
}
} else if (key === 'class') { // 对class做特殊处理, className的性能比setAttribute好得多
el.className = nextValue || ''
} else if (shouldSetAsProps(el, key)) {
const type = typeof el[key]
if (type === 'boolean' && nextValue === '') {
el[key] = true
} else {
el[key] = nextValue
}
} else {
el.setAttribute(key, nextValue)
}
}
}
)
renderer.render(vnode, document.getElementById('app'))
</script>
</html>