Backtestsvuerun-20261009-161443#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 A = our agent, Patch B = the merged fix.
Both patches find the same root cause. In dev builds, root-level template comments turn the root into a fragment marked DEV_ROOT_FRAGMENT, so `vnode.el` is the fragment's start anchor rather than the single real element. Both fix it the same way: walk component subTrees and use `filterSingleRoot` on DEV_ROOT_FRAGMENT nodes, returning the resolved element only when such a fragment was actually found. Otherwise existing `$el` semantics, including multi-root anchors, are unchanged.
Patch A puts this logic in a shared helper, `getComponentRootEl`, in componentRenderUtils. It applies the helper everywhere a user-facing element is derived from a component vnode:
- `$el` on the public instance.
- `setRef` for functional components, where a template ref resolves to `vnode.el` and has the same bug.
- Compat `vnode.elm`.
This covers more of the issue's user-facing surface ("templateRef points to comment"), not just `$el` on stateful components.
Patch A's tests are well targeted and would fail before the change:
- Single-root with a comment, including a reactive update that checks `$el` stays stable.
- Nested components that both have root comments.
- A regression guard that multi-root components still return the fragment anchor.
- A functional-component ref.
- A compat test using a real template with a comment, which exercises the actual compiler output.
Patch B fixes only `$el`. It adds Suspense activeBranch traversal and tests for mounting-time safety and unresolved async roots. That hardening is reasonable but sits beyond the issue's ask. Patch B misses the functional-component template-ref case, which shows the same symptom.
On craft, Patch A's shared helper is cleaner and reusable. Patch B's two-function split (`resolveDevRootEl` returning `undefined` as a sentinel, plus `getDevRootFragmentEl`) is slightly more convoluted.
Overall, Patch A is the more complete fix and has stronger tests.
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
9m 14s
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
206vs 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..f908a7172 100644@@ -1,12 +1,21 @@ import {+ Fragment,+ TestNodeTypes, createApp,+ createBlock,+ createCommentVNode, defineComponent, getCurrentInstance, h,+ nextTick, nodeOps,+ openBlock,+ ref, render,+ serializeInner, shallowReadonly, } from '@vue/runtime-test'+import { PatchFlags } from '@vue/shared' import type { ComponentInternalInstance, ComponentOptions,@@ -510,4 +519,108 @@ describe('component: proxy', () => { render(h(Comp), nodeOps.createElement('div')) expect(`Cannot mutate <script setup> binding "foo"`).toHaveBeenWarned() })++ // dev mode: root level comments turn the template root into a fragment+ test('$el should point to the single element root when root has comments', async () => {+ const msg = ref('foo')+ let childProxy: any+ const Child = {+ mounted() {+ childProxy = this+ },+ render: () => (+ openBlock(),+ createBlock(+ Fragment,+ null,+ [+ createCommentVNode('comment'),+ h('div', { class: 'child' }, msg.value),+ ],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ ),+ }++ const root = nodeOps.createElement('div')+ render(h(Child), root)+ expect(serializeInner(root)).toBe(+ `<!--comment--><div class="child">foo</div>`,+ )+ const div = root.children.find(n => n.type === TestNodeTypes.ELEMENT)+ expect(div).toBeDefined()+ expect(childProxy.$el).toBe(div)++ msg.value = 'bar'+ await nextTick()+ expect(serializeInner(root)).toBe(+ `<!--comment--><div class="child">bar</div>`,+ )+ expect(childProxy.$el).toBe(div)+ })++ test('$el should resolve through nested components with root comments', () => {+ let parentProxy: any+ let childProxy: any+ const Child = {+ mounted() {+ childProxy = this+ },+ render: () => (+ openBlock(),+ createBlock(+ Fragment,+ null,+ [createCommentVNode('child'), h('span')],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ ),+ }+ const Parent = {+ mounted() {+ parentProxy = this+ },+ render: () => (+ openBlock(),+ createBlock(+ Fragment,+ null,+ [createCommentVNode('parent'), h(Child)],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ ),+ }++ const root = nodeOps.createElement('div')+ render(h(Parent), root)+ expect(serializeInner(root)).toBe(`<!--parent--><!--child--><span></span>`)+ const span = root.children.find(n => n.type === TestNodeTypes.ELEMENT)+ expect(span).toBeDefined()+ expect(childProxy.$el).toBe(span)+ expect(parentProxy.$el).toBe(span)+ })++ test('$el should still be the fragment anchor for multi-root components', () => {+ let proxy: any+ const Comp = {+ mounted() {+ proxy = this+ },+ render: () => (+ openBlock(),+ createBlock(+ Fragment,+ null,+ [createCommentVNode('comment'), h('div'), h('div')],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ ),+ }++ const root = nodeOps.createElement('div')+ render(h(Comp), root)+ // first child is the fragment start anchor (empty text node)+ expect(proxy.$el).toBe(root.children[0])+ expect(proxy.$el.type).toBe(TestNodeTypes.TEXT)+ }) })packages/runtime-core/__tests__/rendererTemplateRef.spec.tsindex 53e03c827..e695091df 100644@@ -1,10 +1,15 @@ import {+ Fragment, KeepAlive,+ TestNodeTypes,+ createBlock,+ createCommentVNode, defineAsyncComponent, defineComponent, h, nextTick, nodeOps,+ openBlock, reactive, ref, render,@@ -12,6 +17,7 @@ import { shallowRef, watch, } from '@vue/runtime-test'+import { PatchFlags } from '@vue/shared' describe('api: template refs', () => { it('string ref mount', () => {@@ -719,4 +725,30 @@ describe('api: template refs', () => { await nextTick() expect(instanceRef.value.name).toBe('AsyncComp') })++ // dev mode: root level comments turn the template root into a fragment+ test('ref on functional component with root comments should point to element root', () => {+ const Func = () => (+ openBlock(),+ createBlock(+ Fragment,+ null,+ [createCommentVNode('comment'), h('div', { class: 'func' })],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ )+ const el = ref<any>(null)+ const Comp = {+ setup() {+ return () => h(Func, { ref: el })+ },+ }++ const root = nodeOps.createElement('div')+ render(h(Comp), root)+ expect(serializeInner(root)).toBe(`<!--comment--><div class="func"></div>`)+ const div = root.children.find(n => n.type === TestNodeTypes.ELEMENT)+ expect(div).toBeDefined()+ expect(el.value).toBe(div)+ }) })packages/runtime-core/src/compat/renderFn.tsindex 94c838240..88c0e93d2 100644@@ -38,6 +38,7 @@ import { isCompatEnabled, } from './compatConfig' import { compatModelEventPrefix } from './componentVModel'+import { getComponentRootEl } from '../componentRenderUtils' export function convertLegacyRenderFn( instance: ComponentInternalInstance,@@ -321,7 +322,7 @@ export function defineLegacyVNodeProperties(vnode: VNode): void { Object.defineProperties(vnode, { tag: { get: () => vnode.type }, data: { get: () => vnode.props || {}, set: p => (vnode.props = p) },- elm: { get: () => vnode.el },+ elm: { get: () => getComponentRootEl(vnode) }, componentInstance: { get: getInstance }, child: { get: getInstance }, text: { get: () => (isString(vnode.children) ? vnode.children : null) },packages/runtime-core/src/componentPublicInstance.tsindex 7a8af5871..8e1682a40 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.vnode), $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..faafde28a 100644@@ -472,6 +472,37 @@ function hasPropValueChanged( return nextProp !== prevProp } +/**+ * Resolve the host element exposed to users for a component vnode (e.g. `$el`+ * or a template ref on a functional component).+ * In dev mode, template root level comments are rendered, which turns the+ * template into a fragment root whose `el` is the fragment start anchor. In+ * that case locate the single element root instead.+ */+export function getComponentRootEl(vnode: VNode): VNode['el'] {+ if (__DEV__) {+ let root: VNode = vnode+ let resolved: VNode | undefined+ while (true) {+ if (root.component) {+ if (!root.component.subTree) break+ root = root.component.subTree+ } else if (+ root.patchFlag > 0 &&+ root.patchFlag & PatchFlags.DEV_ROOT_FRAGMENT+ ) {+ const singleRoot = filterSingleRoot(root.children as VNodeArrayChildren)+ if (!singleRoot) break+ root = resolved = singleRoot+ } else {+ break+ }+ }+ if (resolved) return root.el+ }+ return vnode.el+}+ export function updateHOCHostEl( { vnode, parent, suspense }: ComponentInternalInstance, el: typeof vnode.el, // HostNodepackages/runtime-core/src/rendererTemplateRef.tsindex 737c1c8c3..b8f673ca4 100644@@ -23,6 +23,7 @@ import { type SchedulerJob, SchedulerJobFlags } from './scheduler' import { queuePostRenderEffect } from './renderer' import { type ComponentOptions, getComponentPublicInstance } from './component' import { isTemplateRefKey, knownTemplateRefs } from './helpers/useTemplateRef'+import { getComponentRootEl } from './componentRenderUtils' const pendingSetRefMap = new WeakMap<VNodeNormalizedRef, SchedulerJob>() /**@@ -67,7 +68,9 @@ export function setRef( const refValue = vnode.shapeFlag & ShapeFlags.STATEFUL_COMPONENT ? getComponentPublicInstance(vnode.component!)- : vnode.el+ : vnode.shapeFlag & ShapeFlags.FUNCTIONAL_COMPONENT+ ? getComponentRootEl(vnode)+ : vnode.el const value = isUnmount ? null : refValue const { i: owner, r: ref } = rawRefpackages/vue-compat/__tests__/renderFn.spec.tsindex 04d8aaac1..cafd40e72 100644@@ -252,4 +252,22 @@ describe('compat: render function', () => { expect(vm.$el).toBeInstanceOf(HTMLDivElement) expect(vm.$el.outerHTML).toBe(`<div>hello</div>`) })++ // dev mode: root level comments turn the template root into a fragment+ test('vnode.elm / $el of component with root comments', () => {+ let childVNode: any+ const Child = {+ template: `<!-- comment --><div class="child">child</div>`,+ }+ const vm = new Vue({+ render(this: any, h: any) {+ return h('div', [(childVNode = h(Child, { ref: 'child' }))])+ },+ }).$mount()++ const childEl = vm.$el.querySelector('.child')+ expect(childEl).toBeInstanceOf(HTMLDivElement)+ expect(childVNode.elm).toBe(childEl)+ expect((vm.$refs.child as any).$el).toBe(childEl)+ }) })
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),