你想要的 vue 源码分析 · 27
代码 执行 把 parse 的结果进行静态节点标记 结果 参考 剖析 Vue.js 内部运行机制
代码
function optimize(rootAst) {
// 判断是否是静态节点,
function isStatic(node) {
if (node.type === 2) {
return false
}
if (node.type === 3) {
return true
}
return !node.if && !node.for
}
// 标记静态节点
function markStatic(node) {
node.static = isStatic(node)
if (node.type === 1) {
for (let i = 0, l = node.children.length; i < l; i++) {
const child = node.children[i]
markStatic(child)
if (!child.static) {
node.static = false
}
}
if (node.ifConditions) {
for (let i = 1, l = node.ifConditions.length; i < l; i++) {
const block = node.ifConditions[i].block
markStatic(block)
if (!block.static) {
node.static = false
}
}
}
}
}
// 标记静态根
function markStaticRoots(node, isInFor) {
if (node.type === 1) {
if (node.static && node.children.length && !(node.children.length === 1 && node.children[0].type === 3)) {
node.staticRoot = true
return
} else {
node.staticRoot = false
}
if (node.children) {
for (let i = 0, l = node.children.length; i < l; i++) {
markStaticRoots(node.children[i], isInFor || !!node.for)
}
}
if (node.ifConditions) {
for (let i = 1, l = node.ifConditions.length; i < l; i++) {
markStaticRoots(node.ifConditions[i].block, isInFor)
}
}
}
}
markStatic(rootAst)
markStaticRoots(rootAst, false)
return rootAst
}
执行
把 parse 的结果进行静态节点标记
var html = '<div :class="obj.name" class="test" data-name="div" v-if="index>0" v-for="(item,index) in arr"><!-- hello --><img src="logo.png"/><p>hello world{{name}}</p></div>'
const ast = parse(html)
var optimize = optimize(ast)
console.log(optimize)
结果

参考
即可发布评论!
暂无评论
确认评论邮箱
邀请制评论