Skip to content

Commit 20c9d26

Browse files
authored
fix(compiler-core): avoid leaking slot branch keys (#15051)
close #15048
1 parent 7da6334 commit 20c9d26

9 files changed

Lines changed: 255 additions & 11 deletions

File tree

‎packages/compiler-core/__tests__/transforms/__snapshots__/transformElement.spec.ts.snap‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,20 @@ return function render(_ctx, _cache) {
121121
}"
122122
`;
123123

124+
exports[`compiler: v-for > codegen > template v-for key injection with single slot child 1`] = `
125+
"const _Vue = Vue
126+
127+
return function render(_ctx, _cache) {
128+
with (_ctx) {
129+
const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createElementBlock: _createElementBlock, renderSlot: _renderSlot } = _Vue
130+
131+
return (_openBlock(true), _createElementBlock(_Fragment, null, _renderList(items, (item) => {
132+
return _renderSlot($slots, "default", {}, undefined, undefined, item.id)
133+
}), 128 /* KEYED_FRAGMENT */))
134+
}
135+
}"
136+
`;
137+
124138
exports[`compiler: v-for > codegen > template v-for w/ <slot/> 1`] = `
125139
"const _Vue = Vue
126140

‎packages/compiler-core/__tests__/transforms/__snapshots__/vFor.spec.ts.snap‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,20 @@ return function render(_ctx, _cache) {
121121
}"
122122
`;
123123

124+
exports[`compiler: v-for > codegen > template v-for key injection with single slot child 1`] = `
125+
"const _Vue = Vue
126+
127+
return function render(_ctx, _cache) {
128+
with (_ctx) {
129+
const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createElementBlock: _createElementBlock, renderSlot: _renderSlot } = _Vue
130+
131+
return (_openBlock(true), _createElementBlock(_Fragment, null, _renderList(items, (item) => {
132+
return _renderSlot($slots, "default", {}, undefined, undefined, item.id)
133+
}), 128 /* KEYED_FRAGMENT */))
134+
}
135+
}"
136+
`;
137+
124138
exports[`compiler: v-for > codegen > template v-for w/ <slot/> 1`] = `
125139
"const _Vue = Vue
126140

‎packages/compiler-core/__tests__/transforms/__snapshots__/vIf.spec.ts.snap‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ return function render(_ctx, _cache) {
8080
const { renderSlot: _renderSlot, createCommentVNode: _createCommentVNode } = _Vue
8181
8282
return ok
83-
? _renderSlot($slots, "default", { key: 0 })
83+
? _renderSlot($slots, "default", {}, undefined, undefined, 0)
8484
: _createCommentVNode("v-if", true)
8585
}
8686
}"
@@ -140,7 +140,21 @@ return function render(_ctx, _cache) {
140140
const { renderSlot: _renderSlot, createCommentVNode: _createCommentVNode } = _Vue
141141
142142
return ok
143-
? _renderSlot($slots, "default", { key: 0 })
143+
? _renderSlot($slots, "default", {}, undefined, undefined, 0)
144+
: _createCommentVNode("v-if", true)
145+
}
146+
}"
147+
`;
148+
149+
exports[`compiler: v-if > codegen > v-if on <slot/> with v-bind 1`] = `
150+
"const _Vue = Vue
151+
152+
return function render(_ctx, _cache) {
153+
with (_ctx) {
154+
const { normalizeProps: _normalizeProps, guardReactiveProps: _guardReactiveProps, renderSlot: _renderSlot, createCommentVNode: _createCommentVNode } = _Vue
155+
156+
return ok
157+
? _renderSlot($slots, "default", _normalizeProps(_guardReactiveProps(items)), undefined, undefined, 0)
144158
: _createCommentVNode("v-if", true)
145159
}
146160
}"

‎packages/compiler-core/__tests__/transforms/vFor.spec.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -918,6 +918,34 @@ describe('compiler: v-for', () => {
918918
expect(generate(root).code).toMatchSnapshot()
919919
})
920920

921+
test('template v-for key injection with single slot child', () => {
922+
const {
923+
root,
924+
node: { codegenNode },
925+
} = parseWithForTransform(
926+
'<template v-for="item in items" :key="item.id"><slot/></template>',
927+
)
928+
expect(
929+
assertSharedCodegen(codegenNode, true, true /* custom return */),
930+
).toMatchObject({
931+
source: { content: `items` },
932+
params: [{ content: `item` }],
933+
returns: {
934+
type: NodeTypes.JS_CALL_EXPRESSION,
935+
callee: RENDER_SLOT,
936+
arguments: [
937+
'$slots',
938+
'"default"',
939+
'{}',
940+
'undefined',
941+
'undefined',
942+
{ content: 'item.id' },
943+
],
944+
},
945+
})
946+
expect(generate(root).code).toMatchSnapshot()
947+
})
948+
921949
// #1907
922950
test('template v-for key injection with single child', () => {
923951
const {

‎packages/compiler-core/__tests__/transforms/vIf.spec.ts‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { transform } from '../../src/transform'
33
import { transformIf } from '../../src/transforms/vIf'
44
import { transformElement } from '../../src/transforms/transformElement'
55
import { transformSlotOutlet } from '../../src/transforms/transformSlotOutlet'
6+
import { transformBind } from '../../src/transforms/vBind'
67
import {
78
type CommentNode,
89
type ConditionalExpression,
@@ -509,7 +510,14 @@ describe('compiler: v-if', () => {
509510
expect(codegenNode.consequent).toMatchObject({
510511
type: NodeTypes.JS_CALL_EXPRESSION,
511512
callee: RENDER_SLOT,
512-
arguments: ['$slots', '"default"', createObjectMatcher({ key: `[0]` })],
513+
arguments: [
514+
'$slots',
515+
'"default"',
516+
'{}',
517+
'undefined',
518+
'undefined',
519+
{ content: '0' },
520+
],
513521
})
514522
expect(generate(root).code).toMatchSnapshot()
515523
})
@@ -522,7 +530,41 @@ describe('compiler: v-if', () => {
522530
expect(codegenNode.consequent).toMatchObject({
523531
type: NodeTypes.JS_CALL_EXPRESSION,
524532
callee: RENDER_SLOT,
525-
arguments: ['$slots', '"default"', createObjectMatcher({ key: `[0]` })],
533+
arguments: [
534+
'$slots',
535+
'"default"',
536+
'{}',
537+
'undefined',
538+
'undefined',
539+
{ content: '0' },
540+
],
541+
})
542+
expect(generate(root).code).toMatchSnapshot()
543+
})
544+
545+
test('v-if on <slot/> with v-bind', () => {
546+
const {
547+
root,
548+
node: { codegenNode },
549+
} = parseWithIfTransform(`<slot v-if="ok" v-bind="items"></slot>`, {
550+
directiveTransforms: {
551+
bind: transformBind,
552+
},
553+
})
554+
expect(codegenNode.consequent).toMatchObject({
555+
type: NodeTypes.JS_CALL_EXPRESSION,
556+
callee: RENDER_SLOT,
557+
arguments: [
558+
'$slots',
559+
'"default"',
560+
{
561+
type: NodeTypes.JS_CALL_EXPRESSION,
562+
callee: NORMALIZE_PROPS,
563+
},
564+
'undefined',
565+
'undefined',
566+
{ content: '0' },
567+
],
526568
})
527569
expect(generate(root).code).toMatchSnapshot()
528570
})

‎packages/compiler-core/src/ast.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -488,14 +488,29 @@ export interface DirectiveArgumentNode extends ArrayExpression {
488488
export interface RenderSlotCall extends CallExpression {
489489
callee: typeof RENDER_SLOT
490490
arguments:
491-
// $slots, name, props, fallback
491+
// $slots, name, props, fallback, noSlotted, branchKey
492492
| [string, string | ExpressionNode]
493-
| [string, string | ExpressionNode, PropsExpression]
493+
| [string, string | ExpressionNode, PropsExpression | '{}']
494494
| [
495495
string,
496496
string | ExpressionNode,
497497
PropsExpression | '{}',
498-
TemplateChildNode[],
498+
FunctionExpression | string,
499+
]
500+
| [
501+
string,
502+
string | ExpressionNode,
503+
PropsExpression | '{}',
504+
FunctionExpression | string,
505+
string,
506+
]
507+
| [
508+
string,
509+
string | ExpressionNode,
510+
PropsExpression | '{}',
511+
FunctionExpression | string,
512+
string,
513+
JSChildNode,
499514
]
500515
}
501516

‎packages/compiler-core/src/utils.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,10 @@ export function injectProp(
392392
prop: Property,
393393
context: TransformContext,
394394
): void {
395+
if (node.type !== NodeTypes.VNODE_CALL && injectSlotKey(node, prop)) {
396+
return
397+
}
398+
395399
let propsWithInjection: ObjectExpression | CallExpression | undefined
396400
/**
397401
* 1. mergeProps(...)
@@ -473,6 +477,36 @@ export function injectProp(
473477
}
474478
}
475479

480+
function injectSlotKey(node: RenderSlotCall, prop: Property): boolean {
481+
if (
482+
prop.key.type !== NodeTypes.SIMPLE_EXPRESSION ||
483+
prop.key.content !== 'key'
484+
) {
485+
return false
486+
}
487+
488+
// If the slot already has a user-provided key, avoid injecting the branch
489+
// key so the user key keeps its existing priority.
490+
const props = node.arguments[2]
491+
if (props && !isString(props)) {
492+
const [unnormalizedProps] = getUnnormalizedProps(props as PropsExpression)
493+
if (
494+
unnormalizedProps &&
495+
!isString(unnormalizedProps) &&
496+
unnormalizedProps.type === NodeTypes.JS_OBJECT_EXPRESSION &&
497+
hasProp(prop, unnormalizedProps)
498+
) {
499+
return true
500+
}
501+
}
502+
503+
node.arguments[2] ||= '{}'
504+
node.arguments[3] ||= 'undefined'
505+
node.arguments[4] ||= 'undefined'
506+
node.arguments[5] = prop.value
507+
return true
508+
}
509+
476510
// check existing key to avoid overriding user provided keys
477511
function hasProp(prop: Property, props: ObjectExpression) {
478512
let result = false

‎packages/runtime-core/__tests__/helpers/renderSlot.spec.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,83 @@ describe('renderSlot', () => {
3838
expect(vnode.key).toBe('_default')
3939
})
4040

41+
it('should allow symbol values for compiler-injected slot keys', () => {
42+
const key = Symbol()
43+
const vnode = renderSlot(
44+
{ default: () => [h('div')] },
45+
'default',
46+
{},
47+
undefined,
48+
undefined,
49+
key,
50+
)
51+
expect(vnode.key).toBe('_default')
52+
})
53+
54+
it('should not expose compiler-injected slot keys to slot props', () => {
55+
let receivedProps: any
56+
const props = ['foo', 'bar']
57+
const vnode = renderSlot(
58+
{
59+
default: props => {
60+
receivedProps = props
61+
return [h('div')]
62+
},
63+
},
64+
'default',
65+
props as any,
66+
undefined,
67+
undefined,
68+
'branch',
69+
)
70+
71+
expect(receivedProps).toBe(props)
72+
expect(receivedProps).not.toHaveProperty('key')
73+
expect(vnode.key).toBe('branch')
74+
})
75+
76+
it('should prefer user-provided slot prop keys over compiler-injected keys', () => {
77+
let receivedProps: any
78+
const props = { key: 'user' }
79+
const vnode = renderSlot(
80+
{
81+
default: props => {
82+
receivedProps = props
83+
return [h('div')]
84+
},
85+
},
86+
'default',
87+
props,
88+
undefined,
89+
undefined,
90+
'branch',
91+
)
92+
93+
expect(receivedProps).toBe(props)
94+
expect(vnode.key).toBe('user')
95+
})
96+
97+
it('should preserve compiler-injected slot keys in custom element mode', () => {
98+
setCurrentRenderingInstance({ type: {}, ce: {} } as any)
99+
100+
let vnode = renderSlot({}, 'default', {}, undefined, undefined, 0)
101+
let slot = (vnode.children as any[])[0]
102+
expect(slot.type).toBe('slot')
103+
expect(slot.key).toBe(0)
104+
expect(vnode.patchFlag).toBe(PatchFlags.BAIL)
105+
106+
vnode = renderSlot(
107+
{},
108+
'default',
109+
{ key: 'user' },
110+
undefined,
111+
undefined,
112+
'branch',
113+
)
114+
slot = (vnode.children as any[])[0]
115+
expect(slot.key).toBe('user')
116+
})
117+
41118
it('should render slot fallback', () => {
42119
const vnode = renderSlot({}, 'default', { key: 'foo' }, () => ['fallback'])
43120
expect(vnode.children).toEqual(['fallback'])

‎packages/runtime-core/src/helpers/renderSlot.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import {
1616
isVNode,
1717
openBlock,
1818
} from '../vnode'
19-
import { PatchFlags, SlotFlags, isSymbol } from '@vue/shared'
19+
import { PatchFlags, SlotFlags, extend, isSymbol } from '@vue/shared'
2020
import { warn } from '../warning'
2121
import { isAsyncWrapper } from '../apiAsyncComponent'
2222

@@ -32,24 +32,29 @@ export function renderSlot(
3232
// the compiler and guaranteed to be a function returning an array
3333
fallback?: () => VNodeArrayChildren,
3434
noSlotted?: boolean,
35+
branchKey?: PropertyKey,
3536
): VNode {
3637
if (
3738
currentRenderingInstance!.ce ||
3839
(currentRenderingInstance!.parent &&
3940
isAsyncWrapper(currentRenderingInstance!.parent) &&
4041
currentRenderingInstance!.parent.ce)
4142
) {
42-
const hasProps = Object.keys(props).length > 0
43+
const slotProps =
44+
branchKey != null && props.key == null
45+
? extend({}, props, { key: branchKey })
46+
: props
47+
const hasProps = Object.keys(slotProps).length > 0
4348
// in custom element mode, render <slot/> as actual slot outlets
4449
// wrap it with a fragment because in shadowRoot: false mode the slot
4550
// element gets replaced by injected content
46-
if (name !== 'default') props.name = name
51+
if (name !== 'default') slotProps.name = name
4752
return (
4853
openBlock(),
4954
createBlock(
5055
Fragment,
5156
null,
52-
[createVNode('slot', props, fallback && fallback())],
57+
[createVNode('slot', slotProps, fallback && fallback())],
5358
hasProps ? PatchFlags.BAIL : PatchFlags.STABLE_FRAGMENT,
5459
)
5560
)
@@ -80,6 +85,7 @@ export function renderSlot(
8085
const validSlotContent = slot && ensureValidVNode(slot(props))
8186
const slotKey =
8287
props.key ||
88+
branchKey ||
8389
// slot content array of a dynamic conditional slot may have a branch
8490
// key attached in the `createSlots` helper, respect that
8591
(validSlotContent && (validSlotContent as any).key)

0 commit comments

Comments
 (0)