Backtestsvuerun-20261013-093701#12680

Issue #12680 Merged fix PR #15313 Run 13 Oct 2026 · run-20261013-093701 vuejs/core

$el of templateRef points to comment VNode instead of first real child of component

Better

Our patch was judged better than the merged fix.

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

Both patches fix the bug the same way. When `$el` is read, they walk through `DEV_ROOT_FRAGMENT` fragments with `filterSingleRoot` to reach the real single root, and both follow nested component roots. The deciding difference is that Patch B wraps the new logic in `__DEV__` (`$el: i => (__DEV__ ? getDevRootFragmentEl(i) : i.vnode.el)`). The issue's reproduction is a `__PROD__` playground: the runtime is the production build, but the template was compiled with the comment-plus-root fragment. With Patch B's gate, that exact scenario still returns the fragment's text anchor, so the reported bug is not fixed. Patch A has no such gate. It explicitly tests both the dev runtime and the prod runtime (`__DEV__ = false`), using real template compilation. Its tests also cover reactivity (a v-if/v-else toggle that changes the root element), an HOC whose root is a component with comment siblings, and event binding on `$el`, which mirrors the issue's click scenario. Patch B adds more edge-case tests (Suspense, async setup, safety during mounting). These are hand-built vnodes run in runtime-test, and they all run under `__DEV__`, so the prod case is never exercised. Patch A's fallback `(root !== subTree && root.el) || el` handles roots that are not yet mounted. Patch B's Suspense traversal is extra hardening that does not affect the core ask. Overall, Patch A addresses the issue as reported, including the prod runtime, and Patch B does not.

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

8m 37s

Wall-clock time in the container

Full test suite

No new failures

1,790 passed · 1 skipped · 1,791 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

94vs 213 merged

Changed lines, ours vs merged

Vue version

3.5.15

Link to minimal reproduction

https://play.vuejs.org/#__PROD__eNp9U9uO2jAQ/ZWpVWlBAqOK9oUCUot4aNWbKI+WqigZghfHjnzJIiH+vWPnUrqs9i32nHN8Zs7kwj7VNW8CsgVbutzK2oPKdLkSzDvBwKEP9VpoWdXGetgcpSrgYE0FD3yWTpH88HFAXCA43GNVq8zjDg8TMPq7CdpjAdeO2TGEzo12HvIoQ1BYPeOOBEs1wcYEH3RGozGs1nARGiAqGIVcmbJHRyVUWKH2C8EmgzxvMhWQv0UV1Yh6d8+zotg2xPsmnUeNNkoqmZ+izM2jz5/dRAz1t0fnW68A17HQ1/i5nLVjpSHSwXfd0QlgWcgGcpU5R+OuM0svC5YqVGtHbfFAtW4KMGtpM+KtAaL2jR6bUGRk7CBL/uiMpkSTW6KbqpYK7c/aSzIu2KLvQ7BMKfP0Nd15G3DS3+dHzE8v3D+6c7wT7JdFh7ZBmk1f85ktkVqI5e3vH3im76FYmSIoQr9S3CENNUSPLexz0AXZvsElt1/Spkld7t32TDm5vqloNM0+4QWjPdu80vo/u3P+PvEoMprisNbxn/g/sDfTKeywMg2CP0pHe1DFPQNvoMpOSGHSJpAzWnp6oN0HeDL2BNPpfeRdrF3iCT3Eex/unwZtbJVczfkH/m7Orn8BgY08Yw==

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:

  1. Open the Playground
  2. Open the console and see that the element referenced by childRef.value.$el is a text VNode
  3. Click on the text "Test" in the preview (Nothing should be logged to the console)
  4. Go into the component "Child.vue" and remove the comment in line 2
  5. After a hot reload (or manual one) childRef.value.$el should 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

Our patch+92 −2
packages/runtime-core/src/componentPublicInstance.tsindex 7a8af5871..6d98f6d19 100644@@ -17,7 +17,9 @@ import {   EMPTY_OBJ,   type IfAny,   NOOP,+  PatchFlags,   type Prettify,+  ShapeFlags,   type UnionToIntersection,   extend,   hasOwn,@@ -51,11 +53,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 { VNodeArrayChildren } from './vnode'  /**  * Custom properties added to component instances in any way and can be accessed through `this`@@ -358,12 +361,36 @@ const getPublicInstance = (   return getPublicInstance(i.parent) } +/**+ * Templates with root-level comments alongside a single root node compile to a+ * fragment flagged with DEV_ROOT_FRAGMENT, whose `el` is the fragment's empty+ * text anchor. Resolve `$el` through such fragments (and through nested+ * component roots) so it points to the actual single root node, matching the+ * result when the comments are stripped.+ */+const getComponentEl = (i: ComponentInternalInstance): any => {+  const el = i.vnode.el+  const subTree = i.subTree+  if (!el || !subTree) return el+  let root = subTree+  while (root.patchFlag > 0 && root.patchFlag & PatchFlags.DEV_ROOT_FRAGMENT) {+    const child = filterSingleRoot(root.children as VNodeArrayChildren, false)+    if (!child) break+    root = child+  }+  if (root.shapeFlag & ShapeFlags.COMPONENT && root.component) {+    return getComponentEl(root.component)+  }+  // the resolved root may not be mounted yet while the parent is patching+  return (root !== subTree && root.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: getComponentEl,     $data: i => i.data,     $props: i => (__DEV__ ? shallowReadonly(i.props) : i.props),     $attrs: i => (__DEV__ ? shallowReadonly(i.attrs) : i.attrs),packages/vue/__tests__/index.spec.tsindex 98f00cf28..60000a37c 100644@@ -506,4 +506,67 @@ describe('compiler + runtime integration', () => {       app.unmount()     })   })++  describe('$el with root-level comments', () => {+    const run = async () => {+      const toggle = ref(true)+      const Child = {+        template: `+          <!-- leading comment -->+          <div v-if="toggle" class="child">Test</div>+          <span v-else class="child">Other</span>+          <!-- trailing comment -->`,+        setup: () => ({ toggle }),+      }+      // HOC whose root is a component with comment siblings+      const Wrapper = {+        components: { Child },+        template: `<!-- wrapper comment --><Child />`,+      }+      const onClick = vi.fn()+      let child: any+      let wrapper: any+      const App = {+        components: { Child, Wrapper },+        template: `<div><Child ref="child" /><Wrapper ref="wrapper" /></div>`,+        mounted(this: any) {+          child = this.$refs.child+          wrapper = this.$refs.wrapper+          child.$el.addEventListener('click', onClick)+        },+      }+      const container = document.createElement('div')+      const app = createApp(App)+      app.mount(container)++      const els = container.querySelectorAll('.child')+      expect(child.$el).toBe(els[0])+      expect(child.$el.tagName).toBe('DIV')+      expect(wrapper.$el).toBe(els[1])+      child.$el.dispatchEvent(new CustomEvent('click'))+      expect(onClick).toHaveBeenCalledTimes(1)++      toggle.value = false+      await nextTick()+      const updated = container.querySelectorAll('.child')+      expect(child.$el).toBe(updated[0])+      expect(child.$el.tagName).toBe('SPAN')+      expect(wrapper.$el).toBe(updated[1])+      expect(wrapper.$el.tagName).toBe('SPAN')+      app.unmount()+    }++    it('should point to the single root element (dev)', async () => {+      await run()+    })++    it('should point to the single root element (prod runtime)', async () => {+      __DEV__ = false+      try {+        await run()+      } finally {+        __DEV__ = true+      }+    })+  }) }) 
Merged fix · PR #15313+211 −2
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),