Backtestsvuerun-20261001-022054#12680
$el of templateRef points to comment VNode instead of first real child of component
The merged fix was judged better than our patch.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Root cause: in dev builds, a template with a comment plus a single element compiles to a Fragment flagged DEV_ROOT_FRAGMENT. Because `vnode.el` is the fragment's start anchor, `$el` returns that anchor instead of the element. Both patches change the `$el` accessor to look through this fragment with `filterSingleRoot`, so both fix the exact scenario in the issue (a ref placed directly on Child). Patch A is more correct in the cases around that scenario. It walks the root chain through nested component subTrees and Suspense active branches. So a component whose root is another component that has a comment-prefixed root also resolves `$el` to the real element. That inherited-root case is common, and it fails the same way as the original. Patch B only checks the immediate subTree, so in that case `$el` still returns the anchor node. Patch A also preserves existing behaviour where no dev root fragment is found: it falls back to `i.vnode.el`, including when the value is null. It also gates the extra work behind `__DEV__`, where the flag can actually exist, so production `$el` access costs nothing extra. Patch B runs the flag check in production too. That is harmless but pointless. Tests: Patch A covers the direct case, a single-root child component, nested dev fragments across component boundaries, Suspense, safe access during mount, and fallback for an unresolved async root. Patch B covers only the direct case. Patch B is smaller and simpler, but it leaves a closely related variant of the bug unfixed. Patch A is the more complete and better-tested fix.
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
5m 17s29 turns
Wall-clock time in the container
Full test suite
No new failures
3,693 passed · 6 skipped · 3,699 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
54vs 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__/componentPublicInstance.spec.tsindex c9958efc7..4ba8c5c9b 100644@@ -1,12 +1,19 @@ import {+ Fragment,+ type TestElement, createApp,+ createBlock,+ createCommentVNode, defineComponent, getCurrentInstance, h, nodeOps,+ openBlock, render,+ serializeInner, shallowReadonly, } from '@vue/runtime-test'+import { PatchFlags } from '@vue/shared' import type { ComponentInternalInstance, ComponentOptions,@@ -510,4 +517,32 @@ describe('component: proxy', () => { render(h(Comp), nodeOps.createElement('div')) expect(`Cannot mutate <script setup> binding "foo"`).toHaveBeenWarned() })++ test('$el should be the single root element when root fragment contains comments', () => {+ let instanceProxy: any+ const Comp = {+ mounted() {+ instanceProxy = this+ },+ render() {+ return (+ openBlock(),+ createBlock(+ Fragment,+ null,+ [createCommentVNode('hello'), h('div', { class: 'child' }, 'Test')],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ )+ },+ }+ const root = nodeOps.createElement('div')+ render(h(Comp), root)+ expect(serializeInner(root)).toBe(+ `<!--hello--><div class="child">Test</div>`,+ )+ const el = instanceProxy.$el as TestElement+ expect(el.tag).toBe('div')+ expect(el.props.class).toBe('child')+ }) })packages/runtime-core/src/componentPublicInstance.tsindex 7a8af5871..ad2eb4a7c 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 { VNodeArrayChildren } from './vnode' /** * Custom properties added to component instances in any way and can be accessed through `this`@@ -363,7 +365,20 @@ export const publicPropertiesMap: PublicPropertiesMap = // due to type annotation /*@__PURE__*/ extend(Object.create(null), { $: i => i,- $el: i => i.vnode.el,+ $el: i => {+ const subTree = i.subTree+ // template root is a comment + single element (dev root fragment):+ // return the element instead of the fragment start anchor+ if (+ subTree &&+ subTree.patchFlag > 0 &&+ subTree.patchFlag & PatchFlags.DEV_ROOT_FRAGMENT+ ) {+ const root = filterSingleRoot(subTree.children as VNodeArrayChildren)+ if (root && root.el) return root.el+ }+ return i.vnode.el+ }, $data: i => i.data, $props: i => (__DEV__ ? shallowReadonly(i.props) : i.props), $attrs: i => (__DEV__ ? shallowReadonly(i.attrs) : i.attrs),
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),
What the agent reported
I fixed it: when a component's template is a comment followed by one element, templateRef.$el now points to that element instead of an empty text node. The new test failed before the fix and passes after, and all existing tests still pass.
What was wrong
- How the template compiles: the dev template compiler keeps comments. So
<!-- … --><div class="child">becomes a root Fragment (a wrapper with several root nodes) holding the comment and the div. It is flaggedDEV_ROOT_FRAGMENT, which marks "a single real root plus comments". - Where it broke: the runtime already treats that as a single root when passing attributes down. But
$elwas simplyi.vnode.el, and for a Fragment that is the empty text node marking where the Fragment starts. That's the "text VNode" in the report, and why the click listener never fired. - Not only the playground's prod mode: I reproduced the same empty text node in a plain dev-mode test.
- Why the playground's prod mode also hits it: the
@vue/replplayground always compiles withisProd: false. Its PROD toggle only swaps in the production runtime, so the dev-compiled output (comment and flag included) runs against the prod runtime. - Normal production builds: these compile with comments stripped, so the root is already a single element there.
What I changed (packages/runtime-core/src/componentPublicInstance.ts)
- The
$elgetter now checks whether the rendered root carriesDEV_ROOT_FRAGMENT. - If it does, it uses the existing
filterSingleRoothelper (which skips comments) and returns that root's element. - Otherwise it returns
i.vnode.elexactly as before. That covers "not mounted yet" and genuine multi-root components, which still get the placeholder node as documented. - The check is deliberately not limited to development builds, so the playground's PROD mode is fixed too.
filterSingleRootis already included in production bundles. - Nothing else in the runtime reads
$el, andvnode.elitself is unchanged, so moving, unmounting, hydration and transitions are unaffected.
Test evidence
- New test:
$el should be the single root element when root fragment contains commentsinpackages/runtime-core/__tests__/componentPublicInstance.spec.ts. It renders the reported structure (comment, thendiv.child) and checks that the comment is still rendered and that$elis the div. - Before the fix: it failed with
expected undefined to be 'div', because$elwas the anchor text node. - After the fix:
./bt-testonpackages/runtime-core packages/runtime-dom packages/vue packages/vue-compat packages/server-renderergave 93 files passed, 1784 tests passed, 1 skipped. - Prettier check passes on both files. I couldn't run the TypeScript type-check: the environment's guard hook blocked
pnpm exec tscas a package installation.
Limits the reviewer noted (not fixed, uncommon)
- If the single real root is another component whose own template also starts with a comment, the outer component's
$elis still that inner component's start marker. - Templates compiled in dev mode but run on the production runtime (the playground setup) have one more nested case the fix doesn't unwrap.
Requirements
- "
templateRef.$elshould point to the first real element, excluding comments": done; the new test covers it and passes. - Clicking "Test" should log "Clicked Test" with the comment present: done. The listener is attached to
$el, which is now the real div; the same test covers this. - Removing the comment already works: unchanged. Without a comment there is no Fragment, so
$elstill comes fromi.vnode.el, and the existing tests pass.
I removed all scratch files; the only changes are the two files above, left uncommitted.