作者: 文章来源:
本文原地址:https://www.mimiwuqi.com/webqianduan/196762.html
目录文章目录近期尤雨溪发布了 5kb 的petite-vue,好奇的我,clone 了他的源码,给大家解析一波。
最近由于工作事情多,所以放缓了原创的脚步!大家谅解
想看我往期手写源码+各种源码解析的可以关注我公众号看我的 GitHub,基本上前端的框架源码都有解析过。
petite-vue是只有 5kb 的 vue,我们先找到仓库,克隆下来:
https://github.com/vuejs/petite-vue
克隆下来后发现,用的是 vite + petite-vue + 多页面形式启动的。
启动命令:
git clone https://github.com/vuejs/petite-vue cd /petite-vue npm i npm run dev
然后打开 http://localhost:3000/即可看到页面:

这里由于都是 html,给我们省去了虚拟 dom 这些东西,可是上面仅仅是处理单个节点,如果是深层级的 dom 节点,就要用到后面的深度优先搜索了。
// process children first before self attrs
walkChildren(el, ctx)
const walkChildren = (node: Element | DocumentFragment, ctx: Context) => {
let child = node.firstChild
while (child) {
child = walk(child, ctx) || child.nextSibling
}
}
当节点上没有v-if之类的属性时,这个时候就去取他们的第一个子节点去做上述的动作,匹配每个v-if、v-for之类的指令
else if (type === 3) {
// Text
const data = (node as Text).data
if (data.includes('{{')) {
let segments: string[] = []
let lastIndex = 0
let match
while ((match = interpolationRE.exec(data))) {
const leading = data.slice(lastIndex, match.index)
if (leading) segments.push(JSON.stringify(leading))
segments.push(`$s(${match[1]})`)
lastIndex = match.index + match[0].length
}
if (lastIndex < data.length) {
segments.push(JSON.stringify(data.slice(lastIndex)))
}
applyDirective(node, text, segments.join('+'), ctx)
}
这个地方很经典,是通过正则匹配,然后一系列操作匹配,最终返回了一个文本字符串。这个代码是挺精髓的,但是由于时间关系这里不细讲了
applyDirective函数:
const applyDirective = (
el: Node,
dir: Directive,
exp: string,
ctx: Context,
arg?: string,
modifiers?: Record<string, true>
) => {
const get = (e = exp) => evaluate(ctx.scope, e, el)
const cleanup = dir({
el,
get,
effect: ctx.effect,
ctx,
exp,
arg,
modifiers
})
if (cleanup) {
ctx.cleanups.push(cleanup)
}
}
接下来nodeType 是 11意味着是一个Fragment节点,那么直接从它的第一个子节点开始即可
} else if (type === 11) {
walkChildren(node as DocumentFragment, ctx)
}
此属性只读且传回一个数值。 有效的数值符合以下的型别: 1-ELEMENT 2-ATTRIBUTE 3-TEXT 4-CDATA 5-ENTITY REFERENCE 6-ENTITY 7-PI (processing instruction) 8-COMMENT 9-DOCUMENT 10-DOCUMENT TYPE 11-DOCUMENT FRAGMENT 12-NOTATION
v-if等模板语法,返回真实的节点这里所有的 dom 节点改变,都是直接通过 js 操作 dom
promise.thenconst p = Promise.resolve() export const nextTick = (fn: () => void) => p.then(fn)
原文链接:点击这里
更多 建站教程 请访问 https://www.mimiwuqi.com/webqianduan/