type MemoExpression,
NodeTypes,
type ObjectExpression,
+ type ParentNode,
type Position,
type Property,
type RenderSlotCall,
}
}
+export function filterNonCommentChildren(
+ node: ParentNode,
+): TemplateChildNode[] {
+ return node.children.filter(n => n.type !== NodeTypes.COMMENT)
+}
+
+export function hasSingleChild(node: ParentNode): boolean {
+ return filterNonCommentChildren(node).length === 1
+}
+
+export function isSingleIfBlock(parent: ParentNode): boolean {
+ // detect cases where the parent v-if is not the only root level node
+ let hasEncounteredIf = false
+ for (const c of filterNonCommentChildren(parent)) {
+ if (
+ c.type === NodeTypes.IF ||
+ (c.type === NodeTypes.ELEMENT && findDir(c, 'if'))
+ ) {
+ // multiple root v-if
+ if (hasEncounteredIf) return false
+ hasEncounteredIf = true
+ } else if (
+ // node before v-if
+ !hasEncounteredIf ||
+ // non else nodes
+ !(c.type === NodeTypes.ELEMENT && findDir(c, /^else(-if)?$/, true))
+ ) {
+ return false
+ }
+ }
+
+ return true
+}
+
export const forAliasRE: RegExp = /([\s\S]*?)\s+(?:in|of)\s+(\S[\s\S]*)/
ElementTypes,
type NodeTransform,
NodeTypes,
- type ParentNode,
type RootNode,
type TemplateChildNode,
createSimpleExpression,
+ filterNonCommentChildren,
findDir,
+ hasSingleChild,
+ isSingleIfBlock,
locStub,
} from '@vue/compiler-dom'
-const filterChild = (node: ParentNode) =>
- node.children.filter(n => n.type !== NodeTypes.COMMENT)
-
-const hasSingleChild = (node: ParentNode): boolean =>
- filterChild(node).length === 1
-
export const ssrInjectFallthroughAttrs: NodeTransform = (node, context) => {
// _attrs is provided as a function argument.
// mark it as a known identifier so that it doesn't get prefixed by
node.tag === 'KeepAlive' ||
node.tag === 'keep-alive')
) {
- const rootChildren = filterChild(context.root)
+ const rootChildren = filterNonCommentChildren(context.root)
if (rootChildren.length === 1 && rootChildren[0] === node) {
if (hasSingleChild(node)) {
injectFallthroughAttrs(node.children[0])
}
if (node.type === NodeTypes.IF_BRANCH && hasSingleChild(node)) {
- // detect cases where the parent v-if is not the only root level node
- let hasEncounteredIf = false
- for (const c of filterChild(parent)) {
- if (
- c.type === NodeTypes.IF ||
- (c.type === NodeTypes.ELEMENT && findDir(c, 'if'))
- ) {
- // multiple root v-if
- if (hasEncounteredIf) return
- hasEncounteredIf = true
- } else if (
- // node before v-if
- !hasEncounteredIf ||
- // non else nodes
- !(c.type === NodeTypes.ELEMENT && findDir(c, /else/, true))
- ) {
- return
- }
+ if (isSingleIfBlock(parent)) {
+ injectFallthroughAttrs(node.children[0])
}
- injectFallthroughAttrs(node.children[0])
} else if (hasSingleChild(parent)) {
injectFallthroughAttrs(node)
}
const n0 = t0()
_renderEffect(() => {
const _key = key.value
- _setDynamicProps(n0, [{ [_key+1]: _unref(foo)[_key+1]() }], true)
+ _setDynamicProps(n0, [{ [_key+1]: _unref(foo)[_key+1]() }])
})
return n0
"
expect(code).contains('const _key = key.value')
expect(code).contains('_key+1')
expect(code).contains(
- '_setDynamicProps(n0, [{ [_key+1]: _unref(foo)[_key+1]() }], true)',
+ '_setDynamicProps(n0, [{ [_key+1]: _unref(foo)[_key+1]() }])',
)
})
export function render(_ctx) {
const n0 = t0()
- _renderEffect(() => _setDynamicProps(n0, [_ctx.obj], true))
+ _renderEffect(() => _setDynamicProps(n0, [_ctx.obj]))
return n0
}"
`;
export function render(_ctx) {
const n0 = t0()
- _renderEffect(() => _setDynamicProps(n0, [{ id: "foo" }, _ctx.obj], true))
+ _renderEffect(() => _setDynamicProps(n0, [{ id: "foo" }, _ctx.obj]))
return n0
}"
`;
export function render(_ctx) {
const n0 = t0()
- _renderEffect(() => _setDynamicProps(n0, [_ctx.obj, { id: "foo" }], true))
+ _renderEffect(() => _setDynamicProps(n0, [_ctx.obj, { id: "foo" }]))
return n0
}"
`;
export function render(_ctx) {
const n0 = t0()
- _renderEffect(() => _setDynamicProps(n0, [{ id: "foo" }, _ctx.obj, { class: "bar" }], true))
+ _renderEffect(() => _setDynamicProps(n0, [{ id: "foo" }, _ctx.obj, { class: "bar" }]))
return n0
}"
`;
exports[`compiler: template ref transform > ref + v-for 1`] = `
"import { createTemplateRefSetter as _createTemplateRefSetter, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<div></div>", true)
+const t0 = _template("<div></div>")
export function render(_ctx) {
const _setTemplateRef = _createTemplateRefSetter()
const n0 = t0()
_renderEffect(() => {
const _key = _ctx.key
- _setDynamicProps(n0, [{ [_key+1]: _ctx.foo[_key+1]() }], true)
+ _setDynamicProps(n0, [{ [_key+1]: _ctx.foo[_key+1]() }])
})
return n0
}"
export function render(_ctx) {
const n0 = t0()
- _renderEffect(() => _setDynamicProps(n0, [{ foo: bar => _ctx.foo = bar }], true))
+ _renderEffect(() => _setDynamicProps(n0, [{ foo: bar => _ctx.foo = bar }]))
return n0
}"
`;
export function render(_ctx) {
const n0 = t0()
- _renderEffect(() => _setDynamicProps(n0, [{ [_camelize(_ctx.foo)]: _ctx.id }], true))
+ _renderEffect(() => _setDynamicProps(n0, [{ [_camelize(_ctx.foo)]: _ctx.id }]))
return n0
}"
`;
export function render(_ctx) {
const n0 = t0()
- _renderEffect(() => _setDynamicProps(n0, [{ ["." + _ctx.fooBar]: _ctx.id }], true))
+ _renderEffect(() => _setDynamicProps(n0, [{ ["." + _ctx.fooBar]: _ctx.id }]))
return n0
}"
`;
_renderEffect(() => {
const _id = _ctx.id
const _title = _ctx.title
- _setDynamicProps(n0, [{ [_id]: _id, [_title]: _title }], true)
+ _setDynamicProps(n0, [{ [_id]: _id, [_title]: _title }])
})
return n0
}"
const n0 = t0()
_renderEffect(() => {
const _id = _ctx.id
- _setDynamicProps(n0, [{ [_id]: _id, foo: "bar", checked: "" }], true)
+ _setDynamicProps(n0, [{ [_id]: _id, foo: "bar", checked: "" }])
})
return n0
}"
export function render(_ctx) {
const n0 = t0()
- _renderEffect(() => _setDynamicProps(n0, [_ctx.obj], true, true))
+ _renderEffect(() => _setDynamicProps(n0, [_ctx.obj], true))
return n0
}"
`;
exports[`compiler: v-for > array de-structured value (with rest) 1`] = `
"import { txt as _txt, toDisplayString as _toDisplayString, setText as _setText, renderEffect as _renderEffect, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<div> </div>", true)
+const t0 = _template("<div> </div>")
export function render(_ctx) {
const n0 = _createFor(() => (_ctx.list), (_for_item0, _for_key0) => {
exports[`compiler: v-for > array de-structured value 1`] = `
"import { txt as _txt, toDisplayString as _toDisplayString, setText as _setText, renderEffect as _renderEffect, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<div> </div>", true)
+const t0 = _template("<div> </div>")
export function render(_ctx) {
const n0 = _createFor(() => (_ctx.list), (_for_item0, _for_key0) => {
exports[`compiler: v-for > basic v-for 1`] = `
"import { txt as _txt, createInvoker as _createInvoker, toDisplayString as _toDisplayString, setText as _setText, renderEffect as _renderEffect, createFor as _createFor, delegateEvents as _delegateEvents, template as _template } from 'vue';
-const t0 = _template("<div> </div>", true)
+const t0 = _template("<div> </div>")
_delegateEvents("click")
export function render(_ctx) {
exports[`compiler: v-for > key only binding pattern 1`] = `
"import { txt as _txt, toDisplayString as _toDisplayString, setText as _setText, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<tr> </tr>", true)
+const t0 = _template("<tr> </tr>")
export function render(_ctx) {
const n0 = _createFor(() => (_ctx.rows), (_for_item0) => {
exports[`compiler: v-for > multi effect 1`] = `
"import { setProp as _setProp, renderEffect as _renderEffect, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<div></div>", true)
+const t0 = _template("<div></div>")
export function render(_ctx) {
const n0 = _createFor(() => (_ctx.items), (_for_item0, _for_key0) => {
exports[`compiler: v-for > nested v-for 1`] = `
"import { setInsertionState as _setInsertionState, txt as _txt, toDisplayString as _toDisplayString, setText as _setText, renderEffect as _renderEffect, createFor as _createFor, template as _template } from 'vue';
const t0 = _template("<span> </span>")
-const t1 = _template("<div></div>", true)
+const t1 = _template("<div></div>")
export function render(_ctx) {
const n0 = _createFor(() => (_ctx.list), (_for_item0) => {
exports[`compiler: v-for > object de-structured value (with rest) 1`] = `
"import { getRestElement as _getRestElement, txt as _txt, toDisplayString as _toDisplayString, setText as _setText, renderEffect as _renderEffect, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<div> </div>", true)
+const t0 = _template("<div> </div>")
export function render(_ctx) {
const n0 = _createFor(() => (_ctx.list), (_for_item0, _for_key0) => {
exports[`compiler: v-for > object de-structured value 1`] = `
"import { txt as _txt, toDisplayString as _toDisplayString, setText as _setText, renderEffect as _renderEffect, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<span> </span>", true)
+const t0 = _template("<span> </span>")
export function render(_ctx) {
const n0 = _createFor(() => (_ctx.items), (_for_item0) => {
exports[`compiler: v-for > object value, key and index 1`] = `
"import { txt as _txt, toDisplayString as _toDisplayString, setText as _setText, renderEffect as _renderEffect, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<div> </div>", true)
+const t0 = _template("<div> </div>")
export function render(_ctx) {
const n0 = _createFor(() => (_ctx.list), (_for_item0, _for_key0, _for_index0) => {
exports[`compiler: v-for > selector pattern 1`] = `
"import { txt as _txt, toDisplayString as _toDisplayString, setText as _setText, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<tr> </tr>", true)
+const t0 = _template("<tr> </tr>")
export function render(_ctx) {
let _selector0_0
exports[`compiler: v-for > selector pattern 2`] = `
"import { setClass as _setClass, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<tr></tr>", true)
+const t0 = _template("<tr></tr>")
export function render(_ctx) {
let _selector0_0
exports[`compiler: v-for > selector pattern 3`] = `
"import { setClass as _setClass, renderEffect as _renderEffect, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<tr></tr>", true)
+const t0 = _template("<tr></tr>")
export function render(_ctx) {
const n0 = _createFor(() => (_ctx.rows), (_for_item0) => {
exports[`compiler: v-for > selector pattern 4`] = `
"import { setClass as _setClass, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<tr></tr>", true)
+const t0 = _template("<tr></tr>")
export function render(_ctx) {
let _selector0_0
exports[`compiler: v-for > v-for aliases w/ complex expressions 1`] = `
"import { getDefaultValue as _getDefaultValue, txt as _txt, toDisplayString as _toDisplayString, setText as _setText, renderEffect as _renderEffect, createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<div> </div>", true)
+const t0 = _template("<div> </div>")
export function render(_ctx) {
const n0 = _createFor(() => (_ctx.list), (_for_item0) => {
exports[`compiler: v-for > w/o value 1`] = `
"import { createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<div>item</div>", true)
+const t0 = _template("<div>item</div>")
export function render(_ctx) {
const n0 = _createFor(() => (_ctx.items), (_for_item0) => {
}"
`;
+exports[`compiler: v-if > multiple v-if at root 1`] = `
+"import { createIf as _createIf, template as _template } from 'vue';
+const t0 = _template("<div>foo</div>")
+const t1 = _template("<div>bar</div>")
+const t2 = _template("<div>baz</div>")
+
+export function render(_ctx) {
+ const n0 = _createIf(() => (_ctx.foo), () => {
+ const n2 = t0()
+ return n2
+ }, () => _createIf(() => (_ctx.bar), () => {
+ const n4 = t1()
+ return n4
+ }))
+ const n6 = _createIf(() => (_ctx.baz), () => {
+ const n8 = t2()
+ return n8
+ })
+ return [n0, n6]
+}"
+`;
+
+exports[`compiler: v-if > template v-if (multiple element) 1`] = `
+"import { createIf as _createIf, template as _template } from 'vue';
+const t0 = _template("<div>hi</div>")
+const t1 = _template("<div>ho</div>")
+
+export function render(_ctx) {
+ const n0 = _createIf(() => (_ctx.foo), () => {
+ const n2 = t0()
+ const n3 = t1()
+ return [n2, n3]
+ })
+ return n0
+}"
+`;
+
+exports[`compiler: v-if > template v-if (single element) 1`] = `
+"import { createIf as _createIf, template as _template } from 'vue';
+const t0 = _template("<div>hi</div>", true)
+
+export function render(_ctx) {
+ const n0 = _createIf(() => (_ctx.foo), () => {
+ const n2 = t0()
+ return n2
+ })
+ return n0
+}"
+`;
+
+exports[`compiler: v-if > template v-if (text) 1`] = `
+"import { createIf as _createIf, template as _template } from 'vue';
+const t0 = _template("hello")
+
+export function render(_ctx) {
+ const n0 = _createIf(() => (_ctx.foo), () => {
+ const n2 = t0()
+ return n2
+ })
+ return n0
+}"
+`;
+
+exports[`compiler: v-if > template v-if (with v-for inside) 1`] = `
+"import { createFor as _createFor, createIf as _createIf, template as _template } from 'vue';
+const t0 = _template("<div></div>")
+
+export function render(_ctx) {
+ const n0 = _createIf(() => (_ctx.foo), () => {
+ const n2 = _createFor(() => (_ctx.list), (_for_item0) => {
+ const n4 = t0()
+ return n4
+ })
+ return n2
+ })
+ return n0
+}"
+`;
+
+exports[`compiler: v-if > template v-if + normal v-else 1`] = `
+"import { createIf as _createIf, template as _template } from 'vue';
+const t0 = _template("<div>hi</div>")
+const t1 = _template("<div>ho</div>")
+const t2 = _template("<div></div>", true)
+
+export function render(_ctx) {
+ const n0 = _createIf(() => (_ctx.foo), () => {
+ const n2 = t0()
+ const n3 = t1()
+ return [n2, n3]
+ }, () => {
+ const n5 = t2()
+ return n5
+ })
+ return n0
+}"
+`;
+
exports[`compiler: v-if > template v-if 1`] = `
"import { txt as _txt, toDisplayString as _toDisplayString, setText as _setText, renderEffect as _renderEffect, createIf as _createIf, template as _template } from 'vue';
const t0 = _template("<div></div>")
const t1 = _template("hello")
-const t2 = _template("<p> </p>", true)
+const t2 = _template("<p> </p>")
export function render(_ctx) {
const n0 = _createIf(() => (_ctx.ok), () => {
exports[`compiler: v-if > v-if + v-else 1`] = `
"import { createIf as _createIf, template as _template } from 'vue';
-const t0 = _template("<div></div>")
-const t1 = _template("<p></p>")
+const t0 = _template("<div></div>", true)
+const t1 = _template("<p></p>", true)
export function render(_ctx) {
const n0 = _createIf(() => (_ctx.ok), () => {
exports[`compiler: v-if > v-if + v-else-if + v-else 1`] = `
"import { createIf as _createIf, template as _template } from 'vue';
-const t0 = _template("<div></div>")
-const t1 = _template("<p></p>")
-const t2 = _template("fine")
+const t0 = _template("<div></div>", true)
+const t1 = _template("<p></p>", true)
+const t2 = _template("fine", true)
export function render(_ctx) {
const n0 = _createIf(() => (_ctx.ok), () => {
exports[`compiler: v-if > v-if + v-else-if 1`] = `
"import { createIf as _createIf, template as _template } from 'vue';
-const t0 = _template("<div></div>")
-const t1 = _template("<p></p>")
+const t0 = _template("<div></div>", true)
+const t1 = _template("<p></p>", true)
export function render(_ctx) {
const n0 = _createIf(() => (_ctx.ok), () => {
return n8
}"
`;
+
+exports[`compiler: v-if > v-if and extra at root 1`] = `
+"import { createIf as _createIf, template as _template } from 'vue';
+const t0 = _template("<div>foo</div>")
+const t1 = _template("<div>bar</div>")
+const t2 = _template("<div>baz</div>")
+
+export function render(_ctx) {
+ const n0 = _createIf(() => (_ctx.foo), () => {
+ const n2 = t0()
+ return n2
+ }, () => _createIf(() => (_ctx.bar), () => {
+ const n4 = t1()
+ return n4
+ }))
+ const n6 = t2()
+ return [n0, n6]
+}"
+`;
export function render(_ctx) {
const n0 = t0()
_applyDynamicModel(n0, () => (_ctx.model), _value => (_ctx.model = _value))
- _renderEffect(() => _setDynamicProps(n0, [_ctx.obj], true))
+ _renderEffect(() => _setDynamicProps(n0, [_ctx.obj]))
return n0
}"
`;
exports[`compiler: v-once > with v-for 1`] = `
"import { createFor as _createFor, template as _template } from 'vue';
-const t0 = _template("<div></div>", true)
+const t0 = _template("<div></div>")
export function render(_ctx) {
const n0 = _createFor(() => (_ctx.list), (_for_item0) => {
exports[`compiler: v-once > with v-if/else 1`] = `
"import { createIf as _createIf, template as _template } from 'vue';
-const t0 = _template("<div></div>")
-const t1 = _template("<p></p>")
+const t0 = _template("<div></div>", true)
+const t1 = _template("<p></p>", true)
export function render(_ctx) {
const n0 = _createIf(() => (_ctx.expr), () => {
],
},
])
- expect(code).contains('_setDynamicProps(n0, [_ctx.obj], true)')
+ expect(code).contains('_setDynamicProps(n0, [_ctx.obj])')
})
test('v-bind="obj" after static prop', () => {
],
},
])
- expect(code).contains(
- '_setDynamicProps(n0, [{ id: "foo" }, _ctx.obj], true)',
- )
+ expect(code).contains('_setDynamicProps(n0, [{ id: "foo" }, _ctx.obj])')
})
test('v-bind="obj" before static prop', () => {
],
},
])
- expect(code).contains(
- '_setDynamicProps(n0, [_ctx.obj, { id: "foo" }], true)',
- )
+ expect(code).contains('_setDynamicProps(n0, [_ctx.obj, { id: "foo" }])')
})
test('v-bind="obj" between static props', () => {
},
])
expect(code).contains(
- '_setDynamicProps(n0, [{ id: "foo" }, _ctx.obj, { class: "bar" }], true)',
+ '_setDynamicProps(n0, [{ id: "foo" }, _ctx.obj, { class: "bar" }])',
)
})
],
})
expect(code).contains(
- '_setDynamicProps(n0, [{ [_id]: _id, [_title]: _title }], true)',
+ '_setDynamicProps(n0, [{ [_id]: _id, [_title]: _title }])',
)
})
],
})
expect(code).contains(
- '_setDynamicProps(n0, [{ [_id]: _id, foo: "bar", checked: "" }], true)',
+ '_setDynamicProps(n0, [{ [_id]: _id, foo: "bar", checked: "" }])',
)
})
expect(code).matchSnapshot()
expect(code).contains('renderEffect')
expect(code).contains(
- `_setDynamicProps(n0, [{ [_camelize(_ctx.foo)]: _ctx.id }], true)`,
+ `_setDynamicProps(n0, [{ [_camelize(_ctx.foo)]: _ctx.id }])`,
)
})
})
expect(code).contains('renderEffect')
expect(code).contains(
- `_setDynamicProps(n0, [{ ["." + _ctx.fooBar]: _ctx.id }], true)`,
+ `_setDynamicProps(n0, [{ ["." + _ctx.fooBar]: _ctx.id }])`,
)
})
<svg v-bind="obj"/>
`)
expect(code).matchSnapshot()
- expect(code).contains('_setDynamicProps(n0, [_ctx.obj], true, true))')
+ expect(code).contains('_setDynamicProps(n0, [_ctx.obj], true))')
})
test('number value', () => {
transformComment,
transformElement,
transformText,
+ transformVFor,
transformVIf,
transformVOnce,
transformVText,
nodeTransforms: [
transformVOnce,
transformVIf,
+ transformVFor,
transformText,
transformElement,
transformComment,
expect(code).matchSnapshot()
})
+ test('multiple v-if at root', () => {
+ const { code, ir } = compileWithVIf(
+ `<div v-if="foo">foo</div><div v-else-if="bar">bar</div><div v-if="baz">baz</div>`,
+ )
+
+ expect(code).toMatchSnapshot()
+ expect(code).contains(`_template("<div>foo</div>")`)
+ expect(code).contains(`_template("<div>bar</div>")`)
+ expect(code).contains(`_template("<div>baz</div>")`)
+ expect([...ir.template.keys()]).toMatchObject([
+ '<div>foo</div>',
+ '<div>bar</div>',
+ '<div>baz</div>',
+ ])
+ })
+
+ test('v-if and extra at root', () => {
+ const { code, ir } = compileWithVIf(
+ `<div v-if="foo">foo</div><div v-else-if="bar">bar</div><div>baz</div>`,
+ )
+
+ expect(code).toMatchSnapshot()
+ expect(code).contains(`_template("<div>foo</div>")`)
+ expect(code).contains(`_template("<div>bar</div>")`)
+ expect(code).contains(`_template("<div>baz</div>")`)
+ expect([...ir.template.keys()]).toMatchObject([
+ '<div>foo</div>',
+ '<div>bar</div>',
+ '<div>baz</div>',
+ ])
+ })
+
test('template v-if', () => {
const { code, ir } = compileWithVIf(
`<template v-if="ok"><div/>hello<p v-text="msg"/></template>`,
})
})
+ test('template v-if (text)', () => {
+ const { code, ir } = compileWithVIf(`<template v-if="foo">hello</template>`)
+
+ expect(code).toMatchSnapshot()
+ expect(code).toContain('_template("hello")')
+ expect([...ir.template.keys()]).toMatchObject(['hello'])
+ })
+
+ test('template v-if (single element)', () => {
+ // single element should not wrap with fragment
+ const { code, ir } = compileWithVIf(
+ `<template v-if="foo"><div>hi</div></template>`,
+ )
+
+ expect(code).toMatchSnapshot()
+ expect(code).toContain('_template("<div>hi</div>", true)')
+ expect([...ir.template.keys()]).toMatchObject(['<div>hi</div>'])
+ })
+
+ test('template v-if (multiple element)', () => {
+ const { code, ir } = compileWithVIf(
+ `<template v-if="foo"><div>hi</div><div>ho</div></template>`,
+ )
+
+ expect(code).toMatchSnapshot()
+ expect(code).toContain('_template("<div>hi</div>")')
+ expect(code).toContain('_template("<div>ho</div>")')
+ expect([...ir.template.keys()]).toMatchObject([
+ '<div>hi</div>',
+ '<div>ho</div>',
+ ])
+ })
+
+ test('template v-if (with v-for inside)', () => {
+ const { code, ir } = compileWithVIf(
+ `<template v-if="foo"><div v-for="i in list"/></template>`,
+ )
+
+ expect(code).toMatchSnapshot()
+ expect(code).toContain('_template("<div></div>")')
+ expect([...ir.template.keys()]).toMatchObject(['<div></div>'])
+ })
+
+ test('template v-if + normal v-else', () => {
+ const { code, ir } = compileWithVIf(
+ `<template v-if="foo"><div>hi</div><div>ho</div></template><div v-else/>`,
+ )
+
+ expect(code).toMatchSnapshot()
+ expect(code).toContain('_template("<div>hi</div>")')
+ expect(code).toContain('_template("<div>ho</div>")')
+ expect(code).toContain('_template("<div></div>", true)')
+ expect([...ir.template.keys()]).toMatchObject([
+ '<div>hi</div>',
+ '<div>ho</div>',
+ '<div></div>',
+ ])
+ })
+
test('dedupe same template', () => {
const { code, ir } = compileWithVIf(
`<div v-if="ok">hello</div><div v-if="ok">hello</div>`,
}
const delegates = genDelegates(context)
- const templates = genTemplates(ir.template, ir.rootTemplateIndex, context)
+ const templates = genTemplates(ir.template, ir.rootTemplateIndexes, context)
const imports = genHelperImports(context) + genAssetImports(context)
const preamble = imports + templates + delegates
helper('setDynamicProps'),
`n${oper.element}`,
genMulti(DELIMITERS_ARRAY, ...values),
- oper.root && 'true',
isSVG && 'true',
),
]
export function genTemplates(
templates: Map<string, number>,
- rootIndex: number | undefined,
+ rootIndexes: Set<number>,
context: CodegenContext,
): string {
const result: string[] = []
// replace import expressions with string concatenation
IMPORT_EXPR_RE,
`" + $1 + "`,
- )}${i === rootIndex ? ', true' : ns ? ', false' : ''}${ns ? `, ${ns}` : ''})\n`,
+ )}${rootIndexes.has(i) ? ', true' : ns ? ', false' : ''}${ns ? `, ${ns}` : ''})\n`,
)
i++
})
source: string
template: Map<string, Namespace>
templateIndexMap: Map<string, number>
- rootTemplateIndex?: number
+ rootTemplateIndexes: Set<number>
component: Set<string>
directive: Set<string>
block: BlockIRNode
type: IRNodeTypes.SET_PROP
element: number
prop: IRProp
- root: boolean
tag: string
}
type: IRNodeTypes.SET_DYNAMIC_PROPS
element: number
props: IRProps[]
- root: boolean
tag: string
}
source: node.source,
template: new Map<string, number>(),
templateIndexMap: new Map<string, number>(),
+ rootTemplateIndexes: new Set(),
component: new Set(),
directive: new Set(),
block: newBlock(node),
ErrorCodes,
NodeTypes,
type PlainElementNode,
+ type RootNode,
type SimpleExpressionNode,
+ type TemplateChildNode,
createCompilerError,
createSimpleExpression,
+ hasSingleChild,
+ isSingleIfBlock,
isStaticArgOf,
isValidHTMLNesting,
} from '@vue/compiler-dom'
getEffectIndex,
)
- let { parent } = context
- while (
- parent &&
- parent.parent &&
- parent.node.type === NodeTypes.ELEMENT &&
- parent.node.tagType === ElementTypes.TEMPLATE
- ) {
- parent = parent.parent
- }
- const singleRoot =
- (context.root === parent &&
- parent.node.children.filter(child => child.type !== NodeTypes.COMMENT)
- .length === 1) ||
- isCustomElement
-
+ const singleRoot = isSingleRoot(context)
if (isComponent) {
transformComponentElement(
node as ComponentNode,
}
}
+function isSingleRoot(
+ context: TransformContext<RootNode | TemplateChildNode>,
+): boolean {
+ if (context.inVFor) {
+ return false
+ }
+
+ let { parent } = context
+ if (
+ parent &&
+ !(hasSingleChild(parent.node) || isSingleIfBlock(parent.node))
+ ) {
+ return false
+ }
+ while (
+ parent &&
+ parent.parent &&
+ parent.node.type === NodeTypes.ELEMENT &&
+ parent.node.tagType === ElementTypes.TEMPLATE
+ ) {
+ parent = parent.parent
+ if (!(hasSingleChild(parent.node) || isSingleIfBlock(parent.node))) {
+ return false
+ }
+ }
+
+ return context.root === parent
+}
+
function transformComponentElement(
node: ComponentNode,
propsResult: PropsResult,
tag,
props: propsResult[0] ? propsResult[1] : [propsResult[1]],
asset,
- root: singleRoot && !context.inVFor,
+ root: singleRoot,
slots: [...context.slots],
once: context.inVOnce,
dynamic: dynamicComponent,
type: IRNodeTypes.SET_DYNAMIC_PROPS,
element: context.reference(),
props: dynamicArgs,
- root: singleRoot,
tag,
},
getEffectIndex,
type: IRNodeTypes.SET_PROP,
element: context.reference(),
prop,
- root: singleRoot,
tag,
},
getEffectIndex,
}
if (singleRoot) {
- context.ir.rootTemplateIndex = context.ir.template.size
+ context.ir.rootTemplateIndexes.add(context.ir.template.size)
}
if (
import {
createComponent,
createDynamicComponent,
+ createIf,
createSlot,
defineVaporComponent,
renderEffect,
expect(host.innerHTML).toBe('<div id="b">2</div>')
})
+ it('should allow attrs to fallthrough on component with comment at root', async () => {
+ const t0 = template('<!--comment-->')
+ const t1 = template('<div>')
+ const { component: Child } = define({
+ props: ['foo'],
+ setup(props: any) {
+ const n0 = t0()
+ const n1 = t1()
+ renderEffect(() => setElementText(n1, props.foo))
+ return [n0, n1]
+ },
+ })
+
+ const foo = ref(1)
+ const id = ref('a')
+ const { host } = define({
+ setup() {
+ return createComponent(
+ Child,
+ {
+ foo: () => foo.value,
+ id: () => id.value,
+ },
+ null,
+ true,
+ )
+ },
+ }).render()
+ expect(host.innerHTML).toBe('<!--comment--><div id="a">1</div>')
+
+ foo.value++
+ await nextTick()
+ expect(host.innerHTML).toBe('<!--comment--><div id="a">2</div>')
+
+ id.value = 'b'
+ await nextTick()
+ expect(host.innerHTML).toBe('<!--comment--><div id="b">2</div>')
+ })
+
+ it('if block', async () => {
+ const t0 = template('<div>foo</div>', true)
+ const t1 = template('<div>bar</div>', true)
+ const t2 = template('<div>baz</div>', true)
+ const { component: Child } = define({
+ setup() {
+ const n0 = createIf(
+ () => true,
+ () => {
+ const n2 = t0()
+ return n2
+ },
+ () =>
+ createIf(
+ () => false,
+ () => {
+ const n4 = t1()
+ return n4
+ },
+ () => {
+ const n7 = t2()
+ return n7
+ },
+ ),
+ )
+ return n0
+ },
+ })
+
+ const id = ref('a')
+ const { host } = define({
+ setup() {
+ return createComponent(
+ Child,
+ {
+ id: () => id.value,
+ },
+ null,
+ true,
+ )
+ },
+ }).render()
+ expect(host.innerHTML).toBe('<div id="a">foo</div><!--if-->')
+ })
+
+ it('should not allow attrs to fallthrough on component with multiple roots', async () => {
+ const t0 = template('<span>')
+ const t1 = template('<div>')
+ const { component: Child } = define({
+ props: ['foo'],
+ setup(props: any) {
+ const n0 = t0()
+ const n1 = t1()
+ renderEffect(() => setElementText(n1, props.foo))
+ return [n0, n1]
+ },
+ })
+
+ const foo = ref(1)
+ const id = ref('a')
+ const { host } = define({
+ setup() {
+ return createComponent(
+ Child,
+ {
+ foo: () => foo.value,
+ id: () => id.value,
+ },
+ null,
+ true,
+ )
+ },
+ }).render()
+ expect(host.innerHTML).toBe('<span></span><div>1</div>')
+ })
+
+ it('should not allow attrs to fallthrough on component with single comment root', async () => {
+ const t0 = template('<!--comment-->')
+ const { component: Child } = define({
+ setup() {
+ const n0 = t0()
+ return [n0]
+ },
+ })
+
+ const id = ref('a')
+ const { host } = define({
+ setup() {
+ return createComponent(Child, { id: () => id.value }, null, true)
+ },
+ }).render()
+ expect(host.innerHTML).toBe('<!--comment-->')
+ })
+
it('should not fallthrough if explicitly pass inheritAttrs: false', async () => {
const t0 = template('<div>', true)
const { component: Child } = define({
EMPTY_OBJ,
ShapeFlags,
invokeArrayFns,
+ isArray,
isFunction,
isString,
} from '@vue/shared'
return nodes
}
}
+
+ // The root node contains comments. It is necessary to filter out
+ // the comment nodes and return a single root node.
+ // align with vdom behavior
+ if (isArray(block)) {
+ let singleRoot: Element | undefined
+ let hasComment = false
+ for (const b of block) {
+ if (b instanceof Comment) {
+ hasComment = true
+ continue
+ }
+ const thisRoot = getRootElement(b)
+ // only return root if there is exactly one eligible root in the array
+ if (!thisRoot || singleRoot) {
+ return
+ }
+ singleRoot = thisRoot
+ }
+ return hasComment ? singleRoot : undefined
+ }
}
}
}
-export function setDynamicProps(
- el: any,
- args: any[],
- root?: boolean,
- isSVG?: boolean,
-): void {
+export function setDynamicProps(el: any, args: any[], isSVG?: boolean): void {
const props = args.length > 1 ? mergeProps(...args) : args[0]
const cacheKey = `$dprops${isApplyingFallthroughProps ? '$' : ''}`
const prevKeys = el[cacheKey] as string[]
- if (root) el.$root = root
if (prevKeys) {
for (const key of prevKeys) {