Backtestsvuerun-20261005-155915#12680

Issue #12680 Merged fix PR #15313 Run 5 Oct 2026 · run-20261005-155915 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.

The reproduction runs in production mode (__PROD__). In that mode, root-level template comments should be stripped at compile time. The bug happens because compiler-sfc reuses the descriptor AST, which was parsed with comments kept, and the compiler's `comments` default follows its own __DEV__ build rather than `isProd`. The leftover comment produces a Fragment root, so `$el` points to the comment node.

Patch A fixes this root cause. It forces `comments: false` when `isProd` unless the user explicitly sets it. It also makes `resolveTemplateAST` re-parse when the reused AST contains comments that must be dropped, and it handles the case where a user-provided AST has no `<template>` wrapper. Its tests cover the scenarios that matter: reused AST, no AST, SSR, inline mode, a user AST, explicit opt-in to comments, and dev mode keeping comments. They assert the root is a single `_createElementBlock("div"` with no Fragment, and they would fail before the change.

Patch B only changes runtime `$el` resolution behind `__DEV__`. It therefore does nothing in the production scenario the issue reports, where the comment-plus-Fragment root still reaches the runtime without the DEV_ROOT_FRAGMENT flag. It also changes long-standing dev `$el` semantics with a fairly complex walk through components and Suspense, which adds risk. Its tests build DEV_ROOT_FRAGMENT vnodes by hand, so they do not reflect the reported prod situation.

Patch A is correct at the root cause and better tested.

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

10m 6s

Wall-clock time in the container

Full test suite

No new failures

3,699 passed · 6 skipped · 3,705 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

151vs 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+148 −3
packages/compiler-sfc/__tests__/compileTemplate.spec.tsindex f9d0807d5..74fe57eb3 100644@@ -6,6 +6,7 @@ import { } from '../src/compileTemplate' import { type SFCTemplateBlock, parse } from '../src/parse' import { compileScript } from '../src'+import { baseParse } from '@vue/compiler-core' import { getPositionInCode } from './utils'  function compile(opts: Omit<SFCTemplateCompileOptions, 'id'>) {@@ -531,3 +532,110 @@ test('prefixing props edge case in inline mode', () => {   expect(content).toMatchSnapshot()   expect(content).toMatch(`__props["Foo"]).Bar`) })++describe('comments in production', () => {+  const src = `<template>+  <!-- leading comment -->+  <div class="child"><!-- nested -->Test</div>+</template>+`++  test('should remove comments when isProd (reused AST)', () => {+    const { descriptor } = parse(src)+    // the descriptor AST is parsed with comments kept in dev builds+    const result = compile({+      filename: 'example.vue',+      source: descriptor.template!.content,+      ast: descriptor.template!.ast,+      isProd: true,+    })+    expect(result.errors.length).toBe(0)+    expect(result.code).not.toMatch(`comment`)+    expect(result.code).not.toMatch(`_Fragment`)+    expect(result.code).not.toMatch(`_createCommentVNode`)+    // single element root so that $el points to the element+    expect(result.code).toMatch(+      `return (_openBlock(), _createElementBlock("div"`,+    )+  })++  test('should remove comments when isProd (no AST)', () => {+    const { descriptor } = parse(src)+    const result = compile({+      filename: 'example.vue',+      source: descriptor.template!.content,+      isProd: true,+    })+    expect(result.errors.length).toBe(0)+    expect(result.code).not.toMatch(`comment`)+    expect(result.code).not.toMatch(`_Fragment`)+  })++  test('should remove comments when isProd (ssr)', () => {+    const { descriptor } = parse(src)+    const result = compile({+      filename: 'example.vue',+      source: descriptor.template!.content,+      ast: descriptor.template!.ast,+      ssr: true,+      ssrCssVars: [],+      isProd: true,+    })+    expect(result.errors.length).toBe(0)+    expect(result.code).not.toMatch(`comment`)+    expect(result.code).not.toMatch(`<!--[-->`)+  })++  test('should remove comments when isProd (inline mode)', () => {+    const { descriptor } = parse(+      `<script setup>const a = 1</script>\n` + src.replace('class="child"', ''),+    )+    const { content } = compileScript(descriptor, {+      id: 'xxx',+      isProd: true,+      inlineTemplate: true,+    })+    expect(content).not.toMatch(`comment`)+    expect(content).not.toMatch(`_Fragment`)+    expect(content).toMatch(`_createElementBlock("div"`)+  })++  test('should remove comments when isProd (user-provided non-SFC AST)', () => {+    const source = `<!-- leading comment -->\n<div class="child">Test</div>`+    const ast = baseParse(source, { comments: true })+    const result = compile({+      filename: 'example.vue',+      source,+      ast,+      isProd: true,+    })+    expect(result.code).not.toMatch(`comment`)+    expect(result.code).not.toMatch(`_Fragment`)+    expect(result.code).toMatch(+      `return (_openBlock(), _createElementBlock("div"`,+    )+  })++  test('should keep comments when explicitly enabled', () => {+    const { descriptor } = parse(src)+    const result = compile({+      filename: 'example.vue',+      source: descriptor.template!.content,+      ast: descriptor.template!.ast,+      isProd: true,+      compilerOptions: { comments: true },+    })+    expect(result.code).toMatch(`leading comment`)+    expect(result.code).toMatch(`nested`)+  })++  test('should keep comments when not isProd', () => {+    const { descriptor } = parse(src)+    const result = compile({+      filename: 'example.vue',+      source: descriptor.template!.content,+      ast: descriptor.template!.ast,+    })+    expect(result.code).toMatch(`leading comment`)+  })+})packages/compiler-sfc/src/compileTemplate.tsindex 6c8ad3988..0dd4d663e 100644@@ -209,9 +209,20 @@ function doCompileTemplate({     inAST = undefined   } +  // The compiler's default for `comments` depends on its own build (__DEV__),+  // which can disagree with `isProd` (e.g. a dev build of the compiler used to+  // compile for production in the browser). Comments should never be kept in+  // production unless explicitly requested.+  const comments =+    compilerOptions.comments != null+      ? compilerOptions.comments+      : isProd+        ? false+        : undefined+   inAST = resolveTemplateAST(inAST, {     compiler,-    compilerOptions,+    compilerOptions: { ...compilerOptions, comments },     ssr,     onError: e => errors.push(e),   })@@ -229,6 +240,7 @@ function doCompileTemplate({     slotted,     sourceMap: true,     ...compilerOptions,+    comments,     hmr: !isProd,     nodeTransforms: nodeTransforms.concat(compilerOptions.nodeTransforms || []),     filename,packages/compiler-sfc/src/template/resolveTemplateAST.tsindex b2897e56d..406efb0d3 100644@@ -4,6 +4,7 @@ import {   NodeTypes,   type ParserOptions,   type RootNode,+  type TemplateChildNode,   createRoot, } from '@vue/compiler-core' import * as CompilerDOM from '@vue/compiler-dom'@@ -21,10 +22,17 @@ export function resolveTemplateAST(     onError: (error: CompilerError) => void   }, ): RootNode | undefined {-  if (!inAST?.transformed) {+  if (+    !inAST ||+    (!inAST.transformed &&+      !(options.compilerOptions?.comments === false && hasComment(inAST)))+  ) {     return inAST   } +  // Re-parse when the AST has already been transformed, or when it contains+  // comments that should be removed (e.g. the SFC descriptor AST was parsed+  // with comments kept but we are compiling for production).   // Parse the full SFC source to preserve template locations relative to it.   const { compiler = CompilerDOM, compilerOptions, ssr, onError } = options   const newAST = (ssr ? CompilerDOM : compiler).parse(inAST.source, {@@ -35,6 +43,23 @@ export function resolveTemplateAST(   })   const template = newAST.children.find(     node => node.type === NodeTypes.ELEMENT && node.tag === 'template',-  ) as ElementNode+  ) as ElementNode | undefined+  // the AST was not produced from a full SFC source (e.g. a user-provided AST+  // of the template content), fall back to compiling from source+  if (!template) {+    return+  }   return createRoot(template.children, inAST.source) }++function hasComment(node: RootNode | TemplateChildNode): boolean {+  if (node.type === NodeTypes.COMMENT) {+    return true+  }+  // only called on untransformed ASTs, where only root and element nodes+  // have children+  if (node.type === NodeTypes.ROOT || node.type === NodeTypes.ELEMENT) {+    return node.children.some(hasComment)+  }+  return false+} 
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),