Backtestsvuerun-20261009-161443#15048
Scoped slot transforms array argument if rendered conditionally
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches find the same root cause: the compiler injects the v-if/v-for branch `key` into slot props via `mergeProps`, which turns an array `v-bind` value into an object. Both fix it the same way, by passing the key as a new 6th argument to `renderSlot`, so the slot receives the props unchanged. Both fix the reported v-if case.
**Why A is better on correctness:** A also handles a closely related path that B misses. When a slot outlet with `v-bind` sits inside v-for, `buildProps` calls `pushRefVForMarker`. That merges `{ref_for: true}` into the slot props and reshapes an array the same way. A skips the marker for `ElementTypes.SLOT` and adds a test confirming that `ref="foo"` on a slot still keeps `ref_for`. Under B, `<slot v-for="list in lists" v-bind="list"/>` still passes an object instead of the array.
**Scope:** A is narrow. It only reroutes the key when the slot props are a single v-bind expression, which is the case that breaks. Plain-object props keep the existing `{ key: 0 }` output, so existing snapshots are unchanged. B reroutes every injected slot key, including slots with no props. That changes existing codegen to `{}, undefined, undefined, 0` and rewrites existing tests and snapshots. B also adds a snapshot to `transformElement.spec.ts.snap` for a vFor test, which looks like misplaced churn.
**Where B is slightly better:** B keeps the old precedence where a user-provided `props.key` wins over the branch key, both at runtime and in the compiler via `hasProp`. A lets the compiler key override a `key` inside the v-bind object, a minor behavior change.
**Tests:** A adds end-to-end runtime tests in `packages/vue` covering v-if toggling, keyed template v-for with element reuse after reordering, and slot v-for, all checking `Array.isArray(props)`. B adds only compiler and unit-level tests.
Overall, A fixes more of the actual bug class with less churn and has stronger tests.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
11m 6s
Wall-clock time in the container
Full test suite
No new failures
3,136 passed · 2 skipped · 3,138 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
248vs 266 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.0
Link to minimal reproduction
Steps to reproduce
- Create a component with a scoped slot that is rendered conditionally
- Pass an array as the sole argument to the slot
What is expected?
Array is rendered normally.
If you render items of that array in v-for loop, you only see items inside that array
What is actually happening?
Array is transformed into object. Items and their indexes are staying the same, key field is added
<img width="383" height="111" alt="Image" src="https://github.com/user-attachments/assets/338bc873-5c20-4fb3-aed9-88f9f8e8cd98" />
System Info
Any additional comments?
key attribute is generated by the compiler for the slot rendered with v-if.
<img width="781" height="243" alt="Image" src="https://github.com/user-attachments/assets/99704cf9-71cb-435d-ba6f-92578b65ff5d" />
While this is not explicitly mentioned in documentation, one can assume that the expectation is that slotProps is always an object, as this is what will be passed to the slot if you use multiple v-bind directives on the slot.
This issue is rather pointing out the difference in behavior of the slot when v-if is present or not present.
The two patches
packages/compiler-core/__tests__/transforms/vFor.spec.tsindex 34991445c..da0becd9b 100644@@ -18,7 +18,12 @@ import { } from '../../src/ast' import { ErrorCodes } from '../../src/errors' import { type CompilerOptions, generate } from '../../src'-import { FRAGMENT, RENDER_LIST, RENDER_SLOT } from '../../src/runtimeHelpers'+import {+ FRAGMENT,+ NORMALIZE_PROPS,+ RENDER_LIST,+ RENDER_SLOT,+} from '../../src/runtimeHelpers' import { PatchFlags } from '@vue/shared' import { createObjectMatcher } from '../testUtils' import { transformVBindShorthand } from '../../src/transforms/transformVBindShorthand'@@ -918,6 +923,60 @@ describe('compiler: v-for', () => { expect(generate(root).code).toMatchSnapshot() }) + test('template v-for w/ <slot v-bind/> should not merge key into props', () => {+ const {+ root,+ node: { codegenNode },+ } = parseWithForTransform(+ '<template v-for="item in items" :key="item.id"><slot v-bind="item.list"/></template>',+ )+ expect(+ assertSharedCodegen(codegenNode, true, true /* custom return */),+ ).toMatchObject({+ returns: {+ type: NodeTypes.JS_CALL_EXPRESSION,+ callee: RENDER_SLOT,+ arguments: [+ '$slots',+ '"default"',+ { callee: NORMALIZE_PROPS },+ 'undefined',+ 'undefined',+ { content: 'item.id' },+ ],+ },+ })+ const code = generate(root).code+ expect(code).not.toMatch('mergeProps')+ expect(code).not.toMatch('ref_for')+ })++ test('v-for on <slot v-bind/> should not merge ref_for into props', () => {+ const {+ root,+ node: { codegenNode },+ } = parseWithForTransform('<slot v-for="item in items" v-bind="item" />')+ expect(+ assertSharedCodegen(codegenNode, false, true /* custom return */),+ ).toMatchObject({+ returns: {+ type: NodeTypes.JS_CALL_EXPRESSION,+ callee: RENDER_SLOT,+ arguments: ['$slots', '"default"', { callee: NORMALIZE_PROPS }],+ },+ })+ const code = generate(root).code+ expect(code).not.toMatch('mergeProps')+ expect(code).not.toMatch('ref_for')+ })++ test('v-for on <slot ref/> should keep ref_for marker', () => {+ const { root } = parseWithForTransform(+ '<slot v-for="item in items" ref="foo" />',+ )+ expect(generate(root).code).toMatch('ref_for: true')+ })+ // #1907 test('template v-for key injection with single child', () => { const {packages/compiler-core/__tests__/transforms/vIf.spec.tsindex fe3aef714..8c59804a3 100644@@ -112,6 +112,52 @@ describe('compiler: v-if', () => { ).toBe(true) }) + test('v-if on <slot/> w/ single v-bind should not merge key into props', () => {+ const {+ root,+ node: { codegenNode },+ } = parseWithIfTransform(`<slot v-if="ok" v-bind="items"></slot>`)+ expect(codegenNode.consequent).toMatchObject({+ type: NodeTypes.JS_CALL_EXPRESSION,+ callee: RENDER_SLOT,+ arguments: [+ '$slots',+ '"default"',+ { callee: NORMALIZE_PROPS },+ 'undefined',+ 'undefined',+ { content: '0' },+ ],+ })+ const code = generate(root).code+ expect(code).not.toMatch('mergeProps')+ expect(code).toMatch(+ `_renderSlot($slots, "default", _normalizeProps(_guardReactiveProps(items)), undefined, undefined, 0)`,+ )+ })++ test('template v-if w/ single <slot v-bind/> child should not merge key into props', () => {+ const {+ root,+ node: { codegenNode },+ } = parseWithIfTransform(+ `<template v-if="ok"><slot name="foo" v-bind="items">fallback</slot></template>`,+ )+ expect(codegenNode.consequent).toMatchObject({+ type: NodeTypes.JS_CALL_EXPRESSION,+ callee: RENDER_SLOT,+ arguments: [+ '$slots',+ '"foo"',+ { callee: NORMALIZE_PROPS },+ { type: NodeTypes.JS_FUNCTION_EXPRESSION },+ 'undefined',+ { content: '0' },+ ],+ })+ expect(generate(root).code).not.toMatch('mergeProps')+ })+ test('v-if + v-else', () => { const { node } = parseWithIfTransform(`<div v-if="ok"/><p v-else/>`) expect(node.type).toBe(NodeTypes.IF)packages/compiler-core/src/transforms/transformElement.tsindex 40f08d45b..775840318 100644@@ -638,7 +638,9 @@ export function buildProps( } // #10696 in case a v-bind object contains ref- pushRefVForMarker()+ // (skipped for slot outlets: the v-bind value is passed to the slot+ // function as-is, and the marker would reshape it, e.g. an array)+ if (node.tagType !== ElementTypes.SLOT) pushRefVForMarker() pushMergeArg() mergeArgs.push(exp) } else {packages/compiler-core/src/utils.tsindex aa426bbab..c80456604 100644@@ -445,6 +445,20 @@ export function injectProp( props.properties.unshift(prop) } propsWithInjection = props+ } else if (+ node.type === NodeTypes.JS_CALL_EXPRESSION &&+ prop.key.type === NodeTypes.SIMPLE_EXPRESSION &&+ prop.key.content === 'key'+ ) {+ // <slot v-bind="expr"> with an injected key: merging the key into the+ // slot props would turn a non-plain-object value (e.g. an array) into an+ // object, so pass the key as a separate argument to renderSlot() instead.+ const args = node.arguments as CallExpression['arguments']+ if (args.length < 4) args[3] = 'undefined'+ if (args.length < 5) args[4] = 'undefined'+ // don't override an already injected key, same as hasProp() above+ if (args.length < 6) args[5] = prop.value+ return } else { // single v-bind with expression, return a merged replacement propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [packages/runtime-core/__tests__/helpers/renderSlot.spec.tsindex bc0678b51..f67f19756 100644@@ -32,6 +32,38 @@ describe('renderSlot', () => { expect(vnode.key).toBe('foo') }) + it('should use the compiler-provided key and pass props as-is', () => {+ const props = ['a', 'b']+ let received+ const vnode = renderSlot(+ {+ default: p => {+ received = p+ return [h('div')]+ },+ },+ 'default',+ props as any,+ undefined,+ undefined,+ 1,+ )+ expect(received).toBe(props)+ expect(vnode.key).toBe('1')+ })++ it('should apply the compiler-provided key to the slot element in custom element mode', () => {+ setCurrentRenderingInstance({ type: {}, ce: {} } as any)+ const props = { foo: 1 }+ const vnode = renderSlot({}, 'default', props, undefined, undefined, 1)+ const slotVNode = (vnode.children as any[])[0]+ expect(slotVNode.type).toBe('slot')+ expect(slotVNode.key).toBe(1)+ expect(slotVNode.props).toEqual({ key: 1, foo: 1 })+ expect(props).toEqual({ foo: 1 })+ setCurrentRenderingInstance({ type: {} } as any)+ })+ it('should allow symbol values for slot prop key', () => { const key = Symbol() const vnode = renderSlot({ default: () => [h('div')] }, 'default', { key })packages/runtime-core/src/helpers/renderSlot.tsindex 8f65f8af4..d6aeccc10 100644@@ -16,7 +16,7 @@ import { isVNode, openBlock, } from '../vnode'-import { PatchFlags, SlotFlags, isSymbol } from '@vue/shared'+import { PatchFlags, SlotFlags, extend, isSymbol } from '@vue/shared' import { warn } from '../warning' import { isAsyncWrapper } from '../apiAsyncComponent' @@ -32,6 +32,9 @@ export function renderSlot( // the compiler and guaranteed to be a function returning an array fallback?: () => VNodeArrayChildren, noSlotted?: boolean,+ // branch / loop key injected by the compiler when the slot props are a+ // single `v-bind="expr"` that must be passed through to the slot as-is+ key?: PropertyKey, ): VNode { if ( currentRenderingInstance!.ce ||@@ -39,6 +42,8 @@ export function renderSlot( isAsyncWrapper(currentRenderingInstance!.parent) && currentRenderingInstance!.parent.ce) ) {+ // the slot outlet is an actual element here, so it still needs the key+ if (key != null) props = extend({ key }, props) const hasProps = Object.keys(props).length > 0 // in custom element mode, render <slot/> as actual slot outlets // wrap it with a fragment because in shadowRoot: false mode the slot@@ -79,7 +84,7 @@ export function renderSlot( try { const validSlotContent = slot && ensureValidVNode(slot(props)) const slotKey =- props.key ||+ (key != null ? key : props.key) || // slot content array of a dynamic conditional slot may have a branch // key attached in the `createSlots` helper, respect that (validSlotContent && (validSlotContent as any).key)packages/vue/__tests__/index.spec.tsindex 6eeff41dd..919c47c51 100644@@ -1,5 +1,5 @@ import { EMPTY_ARR } from '@vue/shared'-import { createApp, nextTick, reactive, ref } from '../src'+import { createApp, nextTick, reactive, ref, shallowRef } from '../src' describe('compiler + runtime integration', () => { it('should support runtime template compilation', () => {@@ -293,6 +293,86 @@ describe('compiler + runtime integration', () => { expect(container.innerHTML).toBe(`<div>2<div>1</div></div>`) }) + test('slot v-if w/ array v-bind should pass the array as-is', async () => {+ const ok = ref(true)+ const items = shallowRef(['a', 'b'])+ const Comp = {+ setup() {+ return { ok, items }+ },+ template: `<div><slot v-if="ok" v-bind="items" /></div>`,+ }+ const App = {+ components: { Comp },+ template: `<Comp v-slot="props">{{ Array.isArray(props) }}:<span v-for="i in props">{{ i }}</span></Comp>`,+ }+ const container = document.createElement('div')+ createApp(App).mount(container)+ expect(container.innerHTML).toBe(+ `<div>true:<span>a</span><span>b</span></div>`,+ )++ items.value = ['a', 'b', 'c']+ await nextTick()+ expect(container.innerHTML).toBe(+ `<div>true:<span>a</span><span>b</span><span>c</span></div>`,+ )++ ok.value = false+ await nextTick()+ expect(container.innerHTML).toBe(`<div><!--v-if--></div>`)++ ok.value = true+ await nextTick()+ expect(container.innerHTML).toBe(+ `<div>true:<span>a</span><span>b</span><span>c</span></div>`,+ )+ })++ test('slot in keyed template v-for w/ array v-bind should pass the array as-is', async () => {+ const rows = shallowRef([+ { id: 1, list: ['a'] },+ { id: 2, list: ['b', 'c'] },+ ])+ const Comp = {+ setup() {+ return { rows }+ },+ template: `<div><template v-for="row in rows" :key="row.id"><slot v-bind="row.list" /></template></div>`,+ }+ const App = {+ components: { Comp },+ template: `<Comp v-slot="props"><p>{{ Array.isArray(props) }}:{{ props.join() }}</p></Comp>`,+ }+ const container = document.createElement('div')+ createApp(App).mount(container)+ expect(container.innerHTML).toBe(`<div><p>true:a</p><p>true:b,c</p></div>`)++ const first = container.querySelector('p')+ rows.value = rows.value.slice().reverse()+ await nextTick()+ expect(container.innerHTML).toBe(`<div><p>true:b,c</p><p>true:a</p></div>`)+ // keyed: the element for row 1 is moved, not re-created+ expect(container.querySelectorAll('p')[1]).toBe(first)+ })++ test('slot v-for w/ array v-bind should pass the array as-is', () => {+ const lists = [['a'], ['b', 'c']]+ const Comp = {+ setup() {+ return { lists }+ },+ template: `<div><slot v-for="list in lists" v-bind="list" /></div>`,+ }+ const App = {+ components: { Comp },+ template: `<Comp v-slot="props"><p>{{ Array.isArray(props) }}:{{ props.join() }}</p></Comp>`,+ }+ const container = document.createElement('div')+ createApp(App).mount(container)+ expect(container.innerHTML).toBe(`<div><p>true:a</p><p>true:b,c</p></div>`)+ })+ // #2413 it('EMPTY_ARR should not change', () => { const App = {
packages/compiler-core/__tests__/transforms/__snapshots__/transformElement.spec.ts.snapindex 3da778eb6..c07237de2 100644@@ -121,6 +121,20 @@ return function render(_ctx, _cache) { }" `; +exports[`compiler: v-for > codegen > template v-for key injection with single slot child 1`] = `+"const _Vue = Vue++return function render(_ctx, _cache) {+ with (_ctx) {+ const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createElementBlock: _createElementBlock, renderSlot: _renderSlot } = _Vue++ return (_openBlock(true), _createElementBlock(_Fragment, null, _renderList(items, (item) => {+ return _renderSlot($slots, "default", {}, undefined, undefined, item.id)+ }), 128 /* KEYED_FRAGMENT */))+ }+}"+`;+ exports[`compiler: v-for > codegen > template v-for w/ <slot/> 1`] = ` "const _Vue = Vue packages/compiler-core/__tests__/transforms/__snapshots__/vFor.spec.ts.snapindex 3da778eb6..c07237de2 100644@@ -121,6 +121,20 @@ return function render(_ctx, _cache) { }" `; +exports[`compiler: v-for > codegen > template v-for key injection with single slot child 1`] = `+"const _Vue = Vue++return function render(_ctx, _cache) {+ with (_ctx) {+ const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createElementBlock: _createElementBlock, renderSlot: _renderSlot } = _Vue++ return (_openBlock(true), _createElementBlock(_Fragment, null, _renderList(items, (item) => {+ return _renderSlot($slots, "default", {}, undefined, undefined, item.id)+ }), 128 /* KEYED_FRAGMENT */))+ }+}"+`;+ exports[`compiler: v-for > codegen > template v-for w/ <slot/> 1`] = ` "const _Vue = Vue packages/compiler-core/__tests__/transforms/__snapshots__/vIf.spec.ts.snapindex 65ee73c46..ed2c8e540 100644@@ -80,7 +80,7 @@ return function render(_ctx, _cache) { const { renderSlot: _renderSlot, createCommentVNode: _createCommentVNode } = _Vue return ok- ? _renderSlot($slots, "default", { key: 0 })+ ? _renderSlot($slots, "default", {}, undefined, undefined, 0) : _createCommentVNode("v-if", true) } }"@@ -140,7 +140,21 @@ return function render(_ctx, _cache) { const { renderSlot: _renderSlot, createCommentVNode: _createCommentVNode } = _Vue return ok- ? _renderSlot($slots, "default", { key: 0 })+ ? _renderSlot($slots, "default", {}, undefined, undefined, 0)+ : _createCommentVNode("v-if", true)+ }+}"+`;++exports[`compiler: v-if > codegen > v-if on <slot/> with v-bind 1`] = `+"const _Vue = Vue++return function render(_ctx, _cache) {+ with (_ctx) {+ const { normalizeProps: _normalizeProps, guardReactiveProps: _guardReactiveProps, renderSlot: _renderSlot, createCommentVNode: _createCommentVNode } = _Vue++ return ok+ ? _renderSlot($slots, "default", _normalizeProps(_guardReactiveProps(items)), undefined, undefined, 0) : _createCommentVNode("v-if", true) } }"packages/compiler-core/__tests__/transforms/vFor.spec.tsindex 34991445c..839d9d358 100644@@ -918,6 +918,34 @@ describe('compiler: v-for', () => { expect(generate(root).code).toMatchSnapshot() }) + test('template v-for key injection with single slot child', () => {+ const {+ root,+ node: { codegenNode },+ } = parseWithForTransform(+ '<template v-for="item in items" :key="item.id"><slot/></template>',+ )+ expect(+ assertSharedCodegen(codegenNode, true, true /* custom return */),+ ).toMatchObject({+ source: { content: `items` },+ params: [{ content: `item` }],+ returns: {+ type: NodeTypes.JS_CALL_EXPRESSION,+ callee: RENDER_SLOT,+ arguments: [+ '$slots',+ '"default"',+ '{}',+ 'undefined',+ 'undefined',+ { content: 'item.id' },+ ],+ },+ })+ expect(generate(root).code).toMatchSnapshot()+ })+ // #1907 test('template v-for key injection with single child', () => { const {packages/compiler-core/__tests__/transforms/vIf.spec.tsindex fe3aef714..677f6b55b 100644@@ -3,6 +3,7 @@ import { transform } from '../../src/transform' import { transformIf } from '../../src/transforms/vIf' import { transformElement } from '../../src/transforms/transformElement' import { transformSlotOutlet } from '../../src/transforms/transformSlotOutlet'+import { transformBind } from '../../src/transforms/vBind' import { type CommentNode, type ConditionalExpression,@@ -509,7 +510,14 @@ describe('compiler: v-if', () => { expect(codegenNode.consequent).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: RENDER_SLOT,- arguments: ['$slots', '"default"', createObjectMatcher({ key: `[0]` })],+ arguments: [+ '$slots',+ '"default"',+ '{}',+ 'undefined',+ 'undefined',+ { content: '0' },+ ], }) expect(generate(root).code).toMatchSnapshot() })@@ -522,7 +530,41 @@ describe('compiler: v-if', () => { expect(codegenNode.consequent).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: RENDER_SLOT,- arguments: ['$slots', '"default"', createObjectMatcher({ key: `[0]` })],+ arguments: [+ '$slots',+ '"default"',+ '{}',+ 'undefined',+ 'undefined',+ { content: '0' },+ ],+ })+ expect(generate(root).code).toMatchSnapshot()+ })++ test('v-if on <slot/> with v-bind', () => {+ const {+ root,+ node: { codegenNode },+ } = parseWithIfTransform(`<slot v-if="ok" v-bind="items"></slot>`, {+ directiveTransforms: {+ bind: transformBind,+ },+ })+ expect(codegenNode.consequent).toMatchObject({+ type: NodeTypes.JS_CALL_EXPRESSION,+ callee: RENDER_SLOT,+ arguments: [+ '$slots',+ '"default"',+ {+ type: NodeTypes.JS_CALL_EXPRESSION,+ callee: NORMALIZE_PROPS,+ },+ 'undefined',+ 'undefined',+ { content: '0' },+ ], }) expect(generate(root).code).toMatchSnapshot() })packages/compiler-core/src/ast.tsindex e3cc5304d..e6da01edb 100644@@ -488,14 +488,29 @@ export interface DirectiveArgumentNode extends ArrayExpression { export interface RenderSlotCall extends CallExpression { callee: typeof RENDER_SLOT arguments:- // $slots, name, props, fallback+ // $slots, name, props, fallback, noSlotted, branchKey | [string, string | ExpressionNode]- | [string, string | ExpressionNode, PropsExpression]+ | [string, string | ExpressionNode, PropsExpression | '{}'] | [ string, string | ExpressionNode, PropsExpression | '{}',- TemplateChildNode[],+ FunctionExpression | string,+ ]+ | [+ string,+ string | ExpressionNode,+ PropsExpression | '{}',+ FunctionExpression | string,+ string,+ ]+ | [+ string,+ string | ExpressionNode,+ PropsExpression | '{}',+ FunctionExpression | string,+ string,+ JSChildNode, ] } packages/compiler-core/src/utils.tsindex aa426bbab..025f6c32d 100644@@ -392,6 +392,10 @@ export function injectProp( prop: Property, context: TransformContext, ): void {+ if (node.type !== NodeTypes.VNODE_CALL && injectSlotKey(node, prop)) {+ return+ }+ let propsWithInjection: ObjectExpression | CallExpression | undefined /** * 1. mergeProps(...)@@ -473,6 +477,36 @@ export function injectProp( } } +function injectSlotKey(node: RenderSlotCall, prop: Property): boolean {+ if (+ prop.key.type !== NodeTypes.SIMPLE_EXPRESSION ||+ prop.key.content !== 'key'+ ) {+ return false+ }++ // If the slot already has a user-provided key, avoid injecting the branch+ // key so the user key keeps its existing priority.+ const props = node.arguments[2]+ if (props && !isString(props)) {+ const [unnormalizedProps] = getUnnormalizedProps(props as PropsExpression)+ if (+ unnormalizedProps &&+ !isString(unnormalizedProps) &&+ unnormalizedProps.type === NodeTypes.JS_OBJECT_EXPRESSION &&+ hasProp(prop, unnormalizedProps)+ ) {+ return true+ }+ }++ node.arguments[2] ||= '{}'+ node.arguments[3] ||= 'undefined'+ node.arguments[4] ||= 'undefined'+ node.arguments[5] = prop.value+ return true+}+ // check existing key to avoid overriding user provided keys function hasProp(prop: Property, props: ObjectExpression) { let result = falsepackages/runtime-core/__tests__/helpers/renderSlot.spec.tsindex bc0678b51..f359f431c 100644@@ -38,6 +38,83 @@ describe('renderSlot', () => { expect(vnode.key).toBe('_default') }) + it('should allow symbol values for compiler-injected slot keys', () => {+ const key = Symbol()+ const vnode = renderSlot(+ { default: () => [h('div')] },+ 'default',+ {},+ undefined,+ undefined,+ key,+ )+ expect(vnode.key).toBe('_default')+ })++ it('should not expose compiler-injected slot keys to slot props', () => {+ let receivedProps: any+ const props = ['foo', 'bar']+ const vnode = renderSlot(+ {+ default: props => {+ receivedProps = props+ return [h('div')]+ },+ },+ 'default',+ props as any,+ undefined,+ undefined,+ 'branch',+ )++ expect(receivedProps).toBe(props)+ expect(receivedProps).not.toHaveProperty('key')+ expect(vnode.key).toBe('branch')+ })++ it('should prefer user-provided slot prop keys over compiler-injected keys', () => {+ let receivedProps: any+ const props = { key: 'user' }+ const vnode = renderSlot(+ {+ default: props => {+ receivedProps = props+ return [h('div')]+ },+ },+ 'default',+ props,+ undefined,+ undefined,+ 'branch',+ )++ expect(receivedProps).toBe(props)+ expect(vnode.key).toBe('user')+ })++ it('should preserve compiler-injected slot keys in custom element mode', () => {+ setCurrentRenderingInstance({ type: {}, ce: {} } as any)++ let vnode = renderSlot({}, 'default', {}, undefined, undefined, 0)+ let slot = (vnode.children as any[])[0]+ expect(slot.type).toBe('slot')+ expect(slot.key).toBe(0)+ expect(vnode.patchFlag).toBe(PatchFlags.BAIL)++ vnode = renderSlot(+ {},+ 'default',+ { key: 'user' },+ undefined,+ undefined,+ 'branch',+ )+ slot = (vnode.children as any[])[0]+ expect(slot.key).toBe('user')+ })+ it('should render slot fallback', () => { const vnode = renderSlot({}, 'default', { key: 'foo' }, () => ['fallback']) expect(vnode.children).toEqual(['fallback'])packages/runtime-core/src/helpers/renderSlot.tsindex 8f65f8af4..2a68ee3e4 100644@@ -16,7 +16,7 @@ import { isVNode, openBlock, } from '../vnode'-import { PatchFlags, SlotFlags, isSymbol } from '@vue/shared'+import { PatchFlags, SlotFlags, extend, isSymbol } from '@vue/shared' import { warn } from '../warning' import { isAsyncWrapper } from '../apiAsyncComponent' @@ -32,6 +32,7 @@ export function renderSlot( // the compiler and guaranteed to be a function returning an array fallback?: () => VNodeArrayChildren, noSlotted?: boolean,+ branchKey?: PropertyKey, ): VNode { if ( currentRenderingInstance!.ce ||@@ -39,17 +40,21 @@ export function renderSlot( isAsyncWrapper(currentRenderingInstance!.parent) && currentRenderingInstance!.parent.ce) ) {- const hasProps = Object.keys(props).length > 0+ const slotProps =+ branchKey != null && props.key == null+ ? extend({}, props, { key: branchKey })+ : props+ const hasProps = Object.keys(slotProps).length > 0 // in custom element mode, render <slot/> as actual slot outlets // wrap it with a fragment because in shadowRoot: false mode the slot // element gets replaced by injected content- if (name !== 'default') props.name = name+ if (name !== 'default') slotProps.name = name return ( openBlock(), createBlock( Fragment, null,- [createVNode('slot', props, fallback && fallback())],+ [createVNode('slot', slotProps, fallback && fallback())], hasProps ? PatchFlags.BAIL : PatchFlags.STABLE_FRAGMENT, ) )@@ -80,6 +85,7 @@ export function renderSlot( const validSlotContent = slot && ensureValidVNode(slot(props)) const slotKey = props.key ||+ branchKey || // slot content array of a dynamic conditional slot may have a branch // key attached in the `createSlots` helper, respect that (validSlotContent && (validSlotContent as any).key)