diff --git a/packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts b/packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts index adc8ed66c77..3dc0005bf6e 100644 --- a/packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts +++ b/packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts @@ -125,4 +125,28 @@ describe('useTemplateRef', () => { __DEV__ = true } }) + + // 12246 + test('should set last element if multiple with same key are defined', () => { + let tRef: ShallowRef + let key = 'refKey' + + const Comp = { + setup() { + tRef = useTemplateRef(key) + }, + render() { + return h('div', [ + h('div', { ref: key }), + h('div', { ref: key }), + h('span', { ref: key }), + ]) + }, + } + + const root = nodeOps.createElement('div') + render(h(Comp), root) + + expect(tRef!.value.tag).toBe('span') + }) }) diff --git a/packages/runtime-core/__tests__/rendererTemplateRef.spec.ts b/packages/runtime-core/__tests__/rendererTemplateRef.spec.ts index 64cb9c63014..68f24055c1c 100644 --- a/packages/runtime-core/__tests__/rendererTemplateRef.spec.ts +++ b/packages/runtime-core/__tests__/rendererTemplateRef.spec.ts @@ -1,4 +1,5 @@ import { + type ShallowRef, defineComponent, h, nextTick, @@ -538,4 +539,27 @@ describe('api: template refs', () => { '
[object Object],[object Object]
', ) }) + + // 12246 + test('should set last element if multiple with same key are defined', () => { + let refKey: ShallowRef + + const Comp = { + setup() { + refKey = ref() + }, + render() { + return h('div', [ + h('div', { ref: refKey }), + h('div', { ref: refKey }), + h('span', { ref: refKey }), + ]) + }, + } + + const root = nodeOps.createElement('div') + render(h(Comp), root) + + expect(refKey!.value.tag).toBe('span') + }) }) diff --git a/packages/runtime-core/src/rendererTemplateRef.ts b/packages/runtime-core/src/rendererTemplateRef.ts index bffe1a25321..29e5d3c0c13 100644 --- a/packages/runtime-core/src/rendererTemplateRef.ts +++ b/packages/runtime-core/src/rendererTemplateRef.ts @@ -115,6 +115,16 @@ export function setRef( } else { if (!isArray(existing)) { if (_isString) { + if (oldRef === ref) { + if (__DEV__ && !__TEST__) { + warn( + 'Duplicate template ref detected:', + ref, + `(${typeof ref}). Ref names must be unique within the same scope.`, + ) + } + return + } refs[ref] = [refValue] if (canSetSetupRef(ref)) { setupState[ref] = refs[ref] @@ -128,6 +138,16 @@ export function setRef( } } } else if (_isString) { + if (oldRef === ref) { + if (__DEV__ && !__TEST__) { + warn( + 'Duplicate template ref detected:', + ref, + `(${typeof ref}). Ref names must be unique within the same scope.`, + ) + } + return + } refs[ref] = value if (canSetSetupRef(ref)) { setupState[ref] = value