Backtestsvuerun-20261021-133314#15048

Issue #15048 Merged fix PR #15051 Run 21 Oct 2026 · run-20261021-133314 vuejs/core

Scoped slot transforms array argument if rendered conditionally

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

Both patches take the same core approach: stop merging the compiler-generated branch key into a single `v-bind` expression on a slot outlet and instead pass the key as a separate sixth `renderSlot()` argument, with `props.key || key` priority at runtime. The independent tests pass on both. The differences are at the edges.

Patch A is more correct. (1) It adds `if (props == null) props = {}` in `renderSlot`. This matters: before either patch, `<slot v-if="ok" v-bind="maybeNull" />` worked because `mergeProps({key:0}, null)` yields an object; after Patch B, the slot now receives `normalizeProps(guardReactiveProps(null))` = `null` and `props.key` (and `Object.keys(props)` in custom-element mode) throws. Patch B therefore regresses a previously working case; Patch A covers it and tests it. (2) Patch A fixes `guardReactiveProps` to `slice()` arrays instead of `extend({}, arr)`, so a reactive array (e.g. an auto-unwrapped `ref([])`) bound to the slot stays an array. Without this, Patch B still turns reactive arrays into index-keyed objects, which is exactly the symptom the issue reports, just via a different code path. (3) Patch A suppresses the `ref_for` marker merge for slot outlets inside `v-for`, so `<slot v-for ... v-bind="arr">` no longer gets `mergeProps({ref_for:true}, arr)`; this is the v-for counterpart of the same array-to-object conversion and is tested.

Scope and craft: Patch A's compiler change is narrow, adding one branch in `injectProp` only for the single-expression case and leaving existing object-props codegen and snapshots untouched. Patch B reroutes all slot key injection through the new argument, requiring snapshot churn, and includes a misplaced snapshot entry (a `compiler: v-for` snapshot added to `transformElement.spec.ts.snap`, apparently duplicated), which is sloppy. Patch B's unit tests for `renderSlot` are reasonable, but Patch A also adds end-to-end compiler+runtime tests covering v-if, v-else, template v-if, template v-for, v-for, objects, nullish, reactive arrays, custom-element mode, and branch toggling.

Patch B's uniform 'key is always a separate arg' design is cleaner conceptually, but the nullish regression and the unhandled reactive-array case outweigh that. Patch A is the better fix.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

14m 36s

Wall-clock time in the container

Full test suite

No new failures

3,142 passed · 2 skipped · 3,144 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

394vs 266 merged

Changed lines, ours vs merged

Vue version

3.5.0

Link to minimal reproduction

https://play.vuejs.org/#eNqFUk1v00AQ/SvDXgxSYqsEDgSnEqBKwAEQReLAoiq1J+m2+6XdtZvK8n/v7Dp2oyptb7Pz3s68mTcd+2Rt3jbIlqz0lRM2gMfQ2FOuhbLGBejA4QZ62DijICNqNkFfjLL7fF7ER6yUfeSa68poH0D5Lazi/9fZV5TSwF/jZP0qe8N1WQztqBE9Aior1wHpBVCmuu3cSxNWnAkCPWcJAug6SAno+8RNfQkri4MabMaCJwkbsc2vvdE0XRfZnFXEFhLdTxsESeRsCQmJ2JoU3n5PueAanI356gqrmyP5a7+LOc5+OfToWuRswsLabTEM8Nn5D9xRPIHK1I0k9jPgb/RGNlHjQPvc6JpkH/CS2m/JCKG3f/zZLqD241BRaGT2ic8ZGRMX9dToD3IX+bv0j+uetjiaeuQ8BocHL1bwL4vRSTaDFLwdg0X2n+7hObNr0e6tLb1d69Nzcp1ORtfosAZtnKJJ76hCBMtLB8VEj8x2fil0/XAme7gsxrqxAfhwJ5FIiuYUeh6MXcKJQzWd1bHeNGEt4q5eECA2B+1f0PP4TC9adNE0WvAif58vPrD+HmmCLos=

Steps to reproduce

  1. Create a component with a scoped slot that is rendered conditionally
  2. 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

Our patch+389 −5
packages/compiler-core/__tests__/transforms/vFor.spec.tsindex 34991445c..2d923e8e9 100644@@ -18,7 +18,13 @@ 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,+  GUARD_REACTIVE_PROPS,+  NORMALIZE_PROPS,+  RENDER_LIST,+  RENDER_SLOT,+} from '../../src/runtimeHelpers' import { PatchFlags } from '@vue/shared' import { createObjectMatcher } from '../testUtils' import { transformVBindShorthand } from '../../src/transforms/transformVBindShorthand'@@ -941,6 +947,75 @@ describe('compiler: v-for', () => {       expect(generate(root).code).toMatchSnapshot()     }) +    test('template v-for key injection w/ <slot/> w/ single v-bind expression', () => {+      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({+        source: { content: `items` },+        params: [{ content: `item` }],+        returns: {+          type: NodeTypes.JS_CALL_EXPRESSION,+          callee: RENDER_SLOT,+          arguments: [+            '$slots',+            '"default"',+            {+              callee: NORMALIZE_PROPS,+              arguments: [+                {+                  callee: GUARD_REACTIVE_PROPS,+                  arguments: [{ content: `item.list` }],+                },+              ],+            },+            'undefined',+            'undefined',+            { content: `item.id` },+          ],+        },+      })+      const code = generate(root).code+      expect(code).not.toContain(`mergeProps`)+      expect(code).not.toContain(`ref_for`)+    })++    test('v-for on <slot/> w/ single v-bind expression', () => {+      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,+              arguments: [+                {+                  callee: GUARD_REACTIVE_PROPS,+                  arguments: [{ content: `item` }],+                },+              ],+            },+          ],+        },+      })+      const code = generate(root).code+      expect(code).not.toContain(`mergeProps`)+      expect(code).not.toContain(`ref_for`)+    })+     test('v-for on <slot/>', () => {       const {         root,packages/compiler-core/__tests__/transforms/vIf.spec.tsindex fe3aef714..7d997398a 100644@@ -26,6 +26,7 @@ import { import {   CREATE_COMMENT,   FRAGMENT,+  GUARD_REACTIVE_PROPS,   MERGE_PROPS,   NORMALIZE_PROPS,   RENDER_SLOT,@@ -112,6 +113,89 @@ describe('compiler: v-if', () => {       ).toBe(true)     }) +    test('v-if on <slot/> w/ single v-bind expression', () => {+      const {+        root,+        node: { codegenNode },+      } = parseWithIfTransform(`<slot v-if="ok" v-bind="items"></slot>`)+      // the bound value must be passed to the slot as-is (not merged with the+      // branch key), the key is passed as a separate argument+      expect(codegenNode.consequent).toMatchObject({+        type: NodeTypes.JS_CALL_EXPRESSION,+        callee: RENDER_SLOT,+        arguments: [+          '$slots',+          '"default"',+          {+            callee: NORMALIZE_PROPS,+            arguments: [+              {+                callee: GUARD_REACTIVE_PROPS,+                arguments: [{ content: `items` }],+              },+            ],+          },+          'undefined',+          'undefined',+          { type: NodeTypes.SIMPLE_EXPRESSION, content: `0` },+        ],+      })+      const code = generate(root).code+      expect(code).not.toContain(`mergeProps`)+      expect(code).toContain(+        `_renderSlot($slots, "default", _normalizeProps(_guardReactiveProps(items)), undefined, undefined, 0)`,+      )+    })++    test('template v-if w/ single <slot/> child w/ single v-bind expression', () => {+      const {+        root,+        node: { codegenNode },+      } = parseWithIfTransform(+        `<template v-if="ok"><slot v-bind="items">fallback</slot></template><template v-else><slot v-bind="items"/></template>`,+      )+      expect(codegenNode.consequent).toMatchObject({+        type: NodeTypes.JS_CALL_EXPRESSION,+        callee: RENDER_SLOT,+        arguments: [+          '$slots',+          '"default"',+          { callee: NORMALIZE_PROPS },+          { type: NodeTypes.JS_FUNCTION_EXPRESSION },+          'undefined',+          { content: `0` },+        ],+      })+      const code = generate(root).code+      expect(code).not.toContain(`mergeProps`)+      expect(code).toContain(+        `_renderSlot($slots, "default", _normalizeProps(_guardReactiveProps(items)), undefined, undefined, 1)`,+      )+    })++    test('v-if on <slot/> w/ single v-bind expression in scoped mode', () => {+      const {+        root,+        node: { codegenNode },+      } = parseWithIfTransform(`<slot v-if="ok" v-bind="items"></slot>`, {+        scopeId: 'data-v-xxxxxxx',+        slotted: false,+      })+      // noSlotted argument generated for scoped css must be preserved+      expect(codegenNode.consequent).toMatchObject({+        callee: RENDER_SLOT,+        arguments: [+          '$slots',+          '"default"',+          { callee: NORMALIZE_PROPS },+          'undefined',+          'true',+          { content: `0` },+        ],+      })+      expect(generate(root).code).not.toContain(`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/ast.tsindex e3cc5304d..b570689cf 100644@@ -497,6 +497,15 @@ export interface RenderSlotCall extends CallExpression {         PropsExpression | '{}',         TemplateChildNode[],       ]+    // $slots, name, props, fallback, noSlotted, key+    | [+        string,+        string | ExpressionNode,+        PropsExpression | '{}',+        FunctionExpression | 'undefined',+        string,+        JSChildNode,+      ] }  export type SlotsExpression = SlotsObjectExpression | DynamicSlotsExpressionpackages/compiler-core/src/transforms/transformElement.tsindex 40f08d45b..a0b217d83 100644@@ -638,7 +638,12 @@ export function buildProps(             }              // #10696 in case a v-bind object contains ref-            pushRefVForMarker()+            // (not for slot outlets: the bound value is passed to the slot+            // as-is, merging the marker would turn e.g. an array into an+            // object)+            if (node.tagType !== ElementTypes.SLOT) {+              pushRefVForMarker()+            }             pushMergeArg()             mergeArgs.push(exp)           } else {packages/compiler-core/src/utils.tsindex aa426bbab..14231974e 100644@@ -445,6 +445,13 @@ export function injectProp(       props.properties.unshift(prop)     }     propsWithInjection = props+  } else if (node.type === NodeTypes.JS_CALL_EXPRESSION) {+    // single v-bind with expression on a slot outlet: the bound value is+    // passed to the slot as-is (it may be e.g. an array), so merging the key+    // into it would change what the slot receives. pass the key as a separate+    // renderSlot() argument instead.+    injectRenderSlotKey(node, prop)+    return   } else {     // single v-bind with expression, return a merged replacement     propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [@@ -473,6 +480,14 @@ export function injectProp(   } } +function injectRenderSlotKey(node: RenderSlotCall, prop: Property): void {+  // renderSlot(slots, name, props, fallback, noSlotted, key)+  const args = node.arguments as CallExpression['arguments']+  if (args.length < 4) args[3] = 'undefined'+  if (args.length < 5) args[4] = 'undefined'+  args[5] = prop.value+}+ // 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..1a2d07211 100644@@ -38,6 +38,45 @@ describe('renderSlot', () => {     expect(vnode.key).toBe('_default')   }) +  it('should pass array props as-is and use the separate key', () => {+    const items = ['a', 'b']+    let received: any+    const vnode = renderSlot(+      {+        default: (props: any) => {+          received = props+          return [h('div')]+        },+      },+      'default',+      items as any,+      undefined,+      undefined,+      1,+    )+    expect(received).toBe(items)+    expect(vnode.key).toBe('1')+  })++  it('should normalize nullish props to an empty object', () => {+    let received: any+    const vnode = renderSlot(+      {+        default: (props: any) => {+          received = props+          return [h('div')]+        },+      },+      'default',+      null as any,+      undefined,+      undefined,+      1,+    )+    expect(received).toEqual({})+    expect(vnode.key).toBe('1')+  })+   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..3e3ed5580 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,13 +32,22 @@ 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` expression, kept separate so that the bound value (e.g. an+  // array) is passed to the slot untouched+  key?: PropertyKey, ): VNode {+  // a single `v-bind` expression is passed through as-is and may be nullish+  if (props == null) props = {}   if (     currentRenderingInstance!.ce ||     (currentRenderingInstance!.parent &&       isAsyncWrapper(currentRenderingInstance!.parent) &&       currentRenderingInstance!.parent.ce)   ) {+    // apply the separately passed key to a copy, as the bound value must not+    // be mutated+    if (key !== undefined) 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@@ -80,6 +89,7 @@ export function renderSlot(     const validSlotContent = slot && ensureValidVNode(slot(props))     const slotKey =       props.key ||+      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/runtime-core/src/vnode.tsindex e9745c503..42a8f0ffb 100644@@ -635,7 +635,12 @@ export function guardReactiveProps(   props: (Data & VNodeProps) | null, ): (Data & VNodeProps) | null {   if (!props) return null-  return isProxy(props) || isInternalObject(props) ? extend({}, props) : props+  return isProxy(props) || isInternalObject(props)+    ? // keep arrays as arrays, e.g. a reactive array bound to `<slot v-bind>`+      isArray(props)+      ? (props.slice() as any)+      : extend({}, props)+    : props }  export function cloneVNode<T, U>(packages/vue/__tests__/index.spec.tsindex 6eeff41dd..e2b0c846f 100644@@ -1,5 +1,11 @@ import { EMPTY_ARR } from '@vue/shared'-import { createApp, nextTick, reactive, ref } from '../src'+import {+  createApp,+  defineCustomElement,+  nextTick,+  reactive,+  ref,+} from '../src'  describe('compiler + runtime integration', () => {   it('should support runtime template compilation', () => {@@ -311,4 +317,140 @@ describe('compiler + runtime integration', () => {     app.mount(root)     expect(root.innerHTML).toBe('<div>60000000100000111</div>')   })++  describe('scoped slot w/ single v-bind expression keeps the bound value', () => {+    const render = async (childTemplate: string, items: any) => {+      const container = document.createElement('div')+      const received: any[] = []+      const Child = {+        props: ['items'],+        data: () => ({ ok: true }),+        template: childTemplate,+      }+      const App = {+        components: { Child },+        setup: () => ({ items, received }),+        template: `<Child :items="items" v-slot="list">{{ received.push(list) && '' }}<span v-for="(i, idx) in list">{{ idx }}:{{ i }},</span></Child>`,+      }+      createApp(App).mount(container)+      await nextTick()+      return { container, received }+    }++    it('v-if on <slot/> w/ array', async () => {+      const { container, received } = await render(+        `<slot v-if="ok" v-bind="items" />`,+        ['a', 'b'],+      )+      expect(container.innerHTML).toBe(`<span>0:a,</span><span>1:b,</span>`)+      expect(Array.isArray(received[0])).toBe(true)+      expect(received[0]).toEqual(['a', 'b'])+    })++    it('v-if / v-else on <slot/> w/ array', async () => {+      const { container, received } = await render(+        `<slot v-if="!ok" /><slot v-else v-bind="items" />`,+        ['a', 'b'],+      )+      expect(container.innerHTML).toBe(`<span>0:a,</span><span>1:b,</span>`)+      expect(received[0]).toEqual(['a', 'b'])+    })++    it('template v-if w/ single <slot/> child w/ array', async () => {+      const { container, received } = await render(+        `<template v-if="ok"><slot v-bind="items" /></template>`,+        ['a', 'b'],+      )+      expect(container.innerHTML).toBe(`<span>0:a,</span><span>1:b,</span>`)+      expect(received[0]).toEqual(['a', 'b'])+    })++    it('template v-for w/ key + <slot/> w/ array', async () => {+      const { container, received } = await render(+        `<template v-for="n in 1" :key="n"><slot v-bind="items" /></template>`,+        ['a', 'b'],+      )+      expect(container.innerHTML).toBe(`<span>0:a,</span><span>1:b,</span>`)+      expect(received[0]).toEqual(['a', 'b'])+    })++    it('v-for on <slot/> w/ array', async () => {+      const { container, received } = await render(+        `<slot v-for="n in 1" v-bind="items" />`,+        ['a', 'b'],+      )+      expect(container.innerHTML).toBe(`<span>0:a,</span><span>1:b,</span>`)+      expect(received[0]).toEqual(['a', 'b'])+    })++    it('v-if on <slot/> w/ object does not leak the branch key', async () => {+      const { container, received } = await render(+        `<slot v-if="ok" v-bind="items" />`,+        { foo: 1 },+      )+      expect(container.innerHTML).toBe(`<span>foo:1,</span>`)+      expect(received[0]).toEqual({ foo: 1 })+    })++    it('v-if on <slot/> w/ nullish value', async () => {+      const { container, received } = await render(+        `<slot v-if="ok" v-bind="items" />`,+        null,+      )+      expect(container.innerHTML).toBe(``)+      expect(received[0]).toEqual({})+    })++    it('<slot/> w/ reactive array, w/ and w/o v-if', async () => {+      for (const tpl of [+        `<slot v-if="ok" v-bind="items" />`,+        `<slot v-bind="items" />`,+      ]) {+        const { container, received } = await render(+          tpl,+          reactive(['a', 'b']),+        )+        expect(container.innerHTML).toBe(`<span>0:a,</span><span>1:b,</span>`)+        expect(Array.isArray(received[0])).toBe(true)+        expect(received[0]).toEqual(['a', 'b'])+      }+    })++    it('custom element: v-if on <slot/> does not mutate the bound object', () => {+      const obj: any = { foo: 'bar' }+      const E = defineCustomElement({+        setup: () => ({ obj, ok: true }),+        template: `<slot v-if="ok" name="x" v-bind="obj" />`,+      })+      customElements.define('slot-v-if-bound-object', E)+      const container = document.createElement('div')+      document.body.appendChild(container)+      container.innerHTML = `<slot-v-if-bound-object></slot-v-if-bound-object>`+      const e = container.childNodes[0] as any+      expect(e.shadowRoot!.innerHTML).toBe(`<slot foo="bar" name="x"></slot>`)+      expect(obj).toEqual({ foo: 'bar' })+      container.remove()+    })++    it('toggling v-if branches of the same slot', async () => {+      const container = document.createElement('div')+      const ok = ref(true)+      const Child = {+        setup: () => ({ ok }),+        template: `<slot v-if="ok" v-bind="['a']" /><slot v-else v-bind="['b', 'c']" />`,+      }+      const App = {+        components: { Child },+        template: `<Child v-slot="list"><i v-for="i in list">{{ i }}</i></Child>`,+      }+      createApp(App).mount(container)+      expect(container.innerHTML).toBe(`<i>a</i>`)+      ok.value = false+      await nextTick()+      expect(container.innerHTML).toBe(`<i>b</i><i>c</i>`)+      ok.value = true+      await nextTick()+      expect(container.innerHTML).toBe(`<i>a</i>`)+    })+  }) }) 
Merged fix · PR #15051+255 −11
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)