Backtestsvuerun-20261021-133314#12680
$el of templateRef points to comment VNode instead of first real child of component
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches share the same core approach: when the component's subTree is a DEV_ROOT_FRAGMENT, use filterSingleRoot to find the lone real root and expose its el as $el, and both follow HOC chains. The decisive difference is that Patch A gates the entire fix behind `__DEV__`, so a template compiled with comments preserved (DEV_ROOT_FRAGMENT set) but running on a production runtime still gets the comment node as `$el`. That is precisely the reporter's setup: the linked reproduction is in the playground's `__PROD__` mode, which pairs a dev-built compiler-sfc with the prod runtime. Patch B explicitly notes this case in its doc comment and resolves it unconditionally, so it fixes the issue as reported; Patch A would leave the reporter's own repro broken. Patch B's resolution also degrades safely: if the inner component has no subTree yet or no dev fragment, `getSingleRootEl` falls through to the existing `vnode.el`. On tests, Patch B adds a compiler-integration test in packages/vue that mirrors the issue (real `<!-- comment --><div>` template, click listener via $el, and v-if swap of the ref target), plus runtime-test unit cases for nested fragments, HOC chains with re-render, and a guard that true multi-root components keep the fragment anchor. Patch A's tests are hand-built block vnodes and include useful Suspense and mounting-safety cases, and its Suspense traversal is a genuine extra that B lacks, but that is adjacent to the ask. Scope and craft are comparable; A's `found` flag and B's mutual recursion are both readable. The `__DEV__` gating is a correctness gap on the reported scenario, so B wins.
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
7m 49s
Wall-clock time in the container
Full test suite
No new failures
1,793 passed · 1 skipped · 1,794 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
158vs 213 merged
Changed lines, ours vs merged
The issue
View on GitHubVue version
3.5.15
Link to minimal reproduction
Steps to reproduce
Hi, I just spent some hours debugging a very strange behavior when accessing the underlying element of a component ref by using templateRef.$el. The component I placed the template ref on had only one root level <div> inside its template, however there was a comment above it. It looks like this leads to the element being referenced by the template ref being the VNode of this comment instead of the <div> element.
Steps to reproduce:
- Open the Playground
- Open the console and see that the element referenced by
childRef.value.$elis a text VNode - Click on the text "Test" in the preview (Nothing should be logged to the console)
- Go into the component "Child.vue" and remove the comment in line 2
- After a hot reload (or manual one)
childRef.value.$elshould point to the div element as logged to the console. Clicking on the text "Test" in the preview should now also log "Clicked Test" to the console
What is expected?
I would expect templateRef.$el to point to the first real element inside the component excluding comments.
What is actually happening?
templateRef.$el points to a VNode for the comment inside the components template.
System Info
_No response_
Any additional comments?
_No response_
The two patches
packages/runtime-core/__tests__/rendererTemplateRef.spec.tsindex 53e03c827..5c82964ca 100644@@ -1,10 +1,14 @@ import {+ Fragment, KeepAlive,+ createBlock,+ createCommentVNode, defineAsyncComponent, defineComponent, h, nextTick, nodeOps,+ openBlock, reactive, ref, render,@@ -12,6 +16,7 @@ import { shallowRef, watch, } from '@vue/runtime-test'+import { PatchFlags } from '@vue/shared' describe('api: template refs', () => { it('string ref mount', () => {@@ -719,4 +724,81 @@ describe('api: template refs', () => { await nextTick() expect(instanceRef.value.name).toBe('AsyncComp') })++ describe('$el with root-level comments', () => {+ const rootFragment = (children: any[]) => (+ openBlock(),+ createBlock(+ Fragment,+ null,+ children,+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ )++ it('should point to the single root element', () => {+ const root = nodeOps.createElement('div')+ const childRef = ref()+ const Child = {+ render: () =>+ rootFragment([+ createCommentVNode('hello'),+ h('div', 'child'),+ createCommentVNode('world'),+ ]),+ }+ render(h({ render: () => h(Child, { ref: childRef }) }), root)+ expect(childRef.value.$el.tag).toBe('div')+ expect(serializeInner(childRef.value.$el)).toBe('child')+ })++ it('should resolve nested dev root fragments', () => {+ const root = nodeOps.createElement('div')+ const childRef = ref()+ const Child = {+ render: () =>+ rootFragment([+ createCommentVNode('outer'),+ rootFragment([createCommentVNode('inner'), h('span', 'nested')]),+ ]),+ }+ render(h({ render: () => h(Child, { ref: childRef }) }), root)+ expect(childRef.value.$el.tag).toBe('span')+ expect(serializeInner(childRef.value.$el)).toBe('nested')+ })++ it('should resolve through HOC chains', async () => {+ const root = nodeOps.createElement('div')+ const outerRef = ref()+ const innerRef = ref()+ const text = ref('foo')+ const Inner = {+ render: () =>+ rootFragment([createCommentVNode('c'), h('div', text.value)]),+ }+ const Outer = {+ render: () => h(Inner, { ref: innerRef }),+ }+ render(h({ render: () => h(Outer, { ref: outerRef }) }), root)+ expect(innerRef.value.$el.tag).toBe('div')+ expect(outerRef.value.$el).toBe(innerRef.value.$el)+ expect(serializeInner(outerRef.value.$el)).toBe('foo')++ text.value = 'bar'+ await nextTick()+ expect(outerRef.value.$el).toBe(innerRef.value.$el)+ expect(serializeInner(outerRef.value.$el)).toBe('bar')+ })++ it('should keep fragment anchor for true multi-root components', () => {+ const root = nodeOps.createElement('div')+ const childRef = ref()+ const Child = {+ render: () => [h('div'), h('span')],+ }+ render(h({ render: () => h(Child, { ref: childRef }) }), root)+ expect(childRef.value.$el.type).toBe('text')+ expect(childRef.value.$el.text).toBe('')+ })+ }) })packages/runtime-core/src/componentPublicInstance.tsindex 7a8af5871..2f1a89acd 100644@@ -51,7 +51,7 @@ import { } from './componentOptions' import type { EmitFn, EmitsOptions } from './componentEmits' import type { SlotsType, UnwrapSlotsType } from './componentSlots'-import { markAttrsAccessed } from './componentRenderUtils'+import { getComponentRootEl, markAttrsAccessed } from './componentRenderUtils' import { currentRenderingInstance } from './componentRenderContext' import { warn } from './warning' import { installCompatInstanceProperties } from './compat/instance'@@ -363,7 +363,7 @@ export const publicPropertiesMap: PublicPropertiesMap = // due to type annotation /*@__PURE__*/ extend(Object.create(null), { $: i => i,- $el: i => i.vnode.el,+ $el: i => getComponentRootEl(i), $data: i => i.data, $props: i => (__DEV__ ? shallowReadonly(i.props) : i.props), $attrs: i => (__DEV__ ? shallowReadonly(i.attrs) : i.attrs),packages/runtime-core/src/componentRenderUtils.tsindex be58e5b0a..9a8be5533 100644@@ -311,6 +311,40 @@ const getChildRoot = (vnode: VNode): [VNode, SetRootFn] => { return [normalizeVNode(childRoot), setRoot] } +/**+ * Resolve the host element exposed as `$el`. When template root-level+ * comments are preserved, a single-element template is compiled into a+ * fragment flagged with DEV_ROOT_FRAGMENT, whose `el` is only the fragment+ * start anchor. In that case expose the single root's element instead.+ * Not gated by `__DEV__` because the flag may come from a dev-compiled template+ * running on a prod runtime.+ */+export function getComponentRootEl(+ instance: ComponentInternalInstance,+): VNode['el'] {+ const subTree = instance.subTree+ // also follow HOC chains (root is another component)+ if (subTree && (isDevRootFragment(subTree) || subTree.component)) {+ const el = getSingleRootEl(subTree)+ if (el) return el+ }+ return instance.vnode.el+}++const isDevRootFragment = (vnode: VNode): boolean =>+ vnode.patchFlag > 0 && !!(vnode.patchFlag & PatchFlags.DEV_ROOT_FRAGMENT)++function getSingleRootEl(vnode: VNode): VNode['el'] {+ if (isDevRootFragment(vnode)) {+ const root = filterSingleRoot(vnode.children as VNodeArrayChildren, false)+ return root ? getSingleRootEl(root) : vnode.el+ }+ if (vnode.component) {+ return getComponentRootEl(vnode.component)+ }+ return vnode.el+}+ export function filterSingleRoot( children: VNodeArrayChildren, recurse = true,packages/vue/__tests__/index.spec.tsindex 98f00cf28..698c43cb2 100644@@ -506,4 +506,42 @@ describe('compiler + runtime integration', () => { app.unmount() }) })++ // root-level comment next to a single root element+ test('$el should resolve to the single root element when template has root comments', async () => {+ const childRef = ref<any>(null)+ const show = ref(true)+ const Child = {+ render: compileToFunction(+ `<!-- comment --><div class="child">Test</div>`,+ ),+ }+ const app = createApp({+ components: { Child },+ setup: () => ({ childRef, show }),+ render: compileToFunction(+ `<Child ref="childRef" v-if="show" />` ++ `<Child ref="childRef" v-else key="b" />`,+ ),+ })+ const container = document.createElement('div')+ app.mount(container)++ const el = childRef.value.$el as HTMLElement+ expect(el).toBe(container.querySelector('.child'))+ expect(el.textContent).toBe('Test')++ // listeners attached via $el should fire on user clicks+ const onClick = vi.fn()+ el.addEventListener('click', onClick)+ container.querySelector<HTMLElement>('.child')!.click()+ expect(onClick).toHaveBeenCalledTimes(1)++ show.value = false+ await nextTick()+ expect(childRef.value.$el).toBe(container.querySelector('.child'))+ expect(childRef.value.$el).not.toBe(el)++ app.unmount()+ }) })
packages/runtime-core/__tests__/componentPublicInstance.spec.tsindex c9958efc7..47a9b2996 100644@@ -1,9 +1,15 @@ import {+ Fragment,+ Suspense,+ TestNodeTypes, createApp,+ createCommentVNode,+ createElementBlock, defineComponent, getCurrentInstance, h, nodeOps,+ openBlock, render, shallowReadonly, } from '@vue/runtime-test'@@ -11,6 +17,7 @@ import type { ComponentInternalInstance, ComponentOptions, } from '../src/component'+import { PatchFlags } from '@vue/shared' describe('component: proxy', () => { test('data', () => {@@ -107,6 +114,168 @@ describe('component: proxy', () => { expect(nextTickThis).toBe(instanceProxy) }) + // #12680+ test('$el should resolve to the real root element when root is a dev comment + single element fragment', () => {+ let instanceProxy: any+ const Comp = {+ setup() {+ return () => (+ openBlock(),+ createElementBlock(+ Fragment,+ null,+ [createCommentVNode(' comment '), h('div', 'real root')],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ )+ },+ mounted() {+ instanceProxy = this+ },+ }+ render(h(Comp), nodeOps.createElement('div'))+ expect(instanceProxy.$el.type).toBe(TestNodeTypes.ELEMENT)+ expect(instanceProxy.$el.tag).toBe('div')+ })++ // #12680+ test('$el should resolve through a single-root child component to its real root element', () => {+ let instanceProxy: any+ const Inner = {+ setup() {+ return () => (+ openBlock(),+ createElementBlock(+ Fragment,+ null,+ [createCommentVNode(' comment '), h('div', 'inner root')],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ )+ },+ }+ const Outer = {+ setup() {+ return () => h(Inner)+ },+ mounted() {+ instanceProxy = this+ },+ }+ render(h(Outer), nodeOps.createElement('div'))+ expect(instanceProxy.$el.type).toBe(TestNodeTypes.ELEMENT)+ expect(instanceProxy.$el.tag).toBe('div')+ })++ // #12680+ test('$el should resolve through nested dev comment fragments across component boundaries', () => {+ let instanceProxy: any+ const Inner = {+ setup() {+ return () => (+ openBlock(),+ createElementBlock(+ Fragment,+ null,+ [createCommentVNode(' comment '), h('div', 'inner root')],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ )+ },+ }+ const Outer = {+ setup() {+ return () => (+ openBlock(),+ createElementBlock(+ Fragment,+ null,+ [createCommentVNode(' comment '), h(Inner)],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ )+ },+ mounted() {+ instanceProxy = this+ },+ }+ render(h(Outer), nodeOps.createElement('div'))+ expect(instanceProxy.$el.type).toBe(TestNodeTypes.ELEMENT)+ expect(instanceProxy.$el.tag).toBe('div')+ })++ test('$el access should be safe while a root child component is mounting', () => {+ const Child = {+ setup() {+ getCurrentInstance()!.parent!.proxy!.$el+ return () => h('div')+ },+ }+ const Parent = {+ setup: () => () => h(Child),+ }++ expect(() => render(h(Parent), nodeOps.createElement('div'))).not.toThrow()+ })++ test('$el should resolve through a Suspense root', () => {+ let instanceProxy: any+ const Inner = {+ setup() {+ return () => (+ openBlock(),+ createElementBlock(+ Fragment,+ null,+ [createCommentVNode(' comment '), h('div', 'inner root')],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ )+ },+ }+ const Outer = {+ setup() {+ return () =>+ h(Suspense, null, {+ default: () => h(Inner),+ })+ },+ mounted() {+ instanceProxy = this+ },+ }++ render(h(Outer), nodeOps.createElement('div'))+ expect(instanceProxy.$el.type).toBe(TestNodeTypes.ELEMENT)+ expect(instanceProxy.$el.tag).toBe('div')+ })++ test('$el should preserve the unresolved async root value without a dev root fragment', () => {+ let instance: ComponentInternalInstance+ let instanceProxy: any+ const Child = {+ name: 'Child',+ async setup() {+ await new Promise(() => {})+ },+ }+ const Parent = {+ setup: () => () => h(Child),+ mounted() {+ instance = getCurrentInstance()!+ instanceProxy = this+ },+ }++ render(h(Parent), nodeOps.createElement('div'))++ expect(+ `A component with async setup() must be nested in a <Suspense>`,+ ).toHaveBeenWarned()+ expect(instance!.vnode.el).toBeNull()+ expect(instanceProxy.$el === instance!.vnode.el).toBe(true)+ })+ test('user attached properties', async () => { let instance: ComponentInternalInstance let instanceProxy: anypackages/runtime-core/src/componentPublicInstance.tsindex 7a8af5871..8a8a5d93b 100644@@ -17,6 +17,7 @@ import { EMPTY_OBJ, type IfAny, NOOP,+ PatchFlags, type Prettify, type UnionToIntersection, extend,@@ -51,11 +52,12 @@ import { } from './componentOptions' import type { EmitFn, EmitsOptions } from './componentEmits' import type { SlotsType, UnwrapSlotsType } from './componentSlots'-import { markAttrsAccessed } from './componentRenderUtils'+import { filterSingleRoot, markAttrsAccessed } from './componentRenderUtils' import { currentRenderingInstance } from './componentRenderContext' import { warn } from './warning' import { installCompatInstanceProperties } from './compat/instance' import type { Directive } from './directives'+import type { VNode, VNodeArrayChildren } from './vnode' /** * Custom properties added to component instances in any way and can be accessed through `this`@@ -358,12 +360,50 @@ const getPublicInstance = ( return getPublicInstance(i.parent) } +// Component and Suspense roots can hide a dev root fragment. Only return a+// resolved element after finding one so other root chains keep their existing+// `$el` semantics.+const resolveDevRootEl = (vnode: VNode): VNode['el'] | undefined => {+ let found = false++ while (true) {+ if (vnode.patchFlag > 0 && vnode.patchFlag & PatchFlags.DEV_ROOT_FRAGMENT) {+ const root = filterSingleRoot(vnode.children as VNodeArrayChildren)+ if (!root) {+ return+ }+ vnode = root+ found = true+ continue+ }++ const component = vnode.component+ if (component && component.subTree) {+ vnode = component.subTree+ continue+ }++ const suspense = vnode.suspense+ if (suspense && suspense.activeBranch) {+ vnode = suspense.activeBranch+ continue+ }++ return found ? vnode.el : undefined+ }+}++const getDevRootFragmentEl = (i: ComponentInternalInstance) => {+ const el = i.subTree && resolveDevRootEl(i.subTree)+ return el === undefined ? i.vnode.el : el+}+ export const publicPropertiesMap: PublicPropertiesMap = // Move PURE marker to new line to workaround compiler discarding it // due to type annotation /*@__PURE__*/ extend(Object.create(null), { $: i => i,- $el: i => i.vnode.el,+ $el: i => (__DEV__ ? getDevRootFragmentEl(i) : i.vnode.el), $data: i => i.data, $props: i => (__DEV__ ? shallowReadonly(i.props) : i.props), $attrs: i => (__DEV__ ? shallowReadonly(i.attrs) : i.attrs),