Backtestsvuerun-20261007-145226#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 fix the core bug the same way. In dev mode, a root-level comment makes the component root a DEV_ROOT_FRAGMENT, and `vnode.el` then points at the fragment's empty text anchor. Both patches walk the component subTree, unwrap DEV_ROOT_FRAGMENTs with `filterSingleRoot`, and return the real element. Both are gated on `__DEV__`, both fall back to `vnode.el` when nothing is resolved, and both handle a missing `subTree` during mount. Correctness: both fix `$el` for the reported scenario, nested component chains, and nested dev fragments. Patch A puts the logic in a shared helper, `getComponentRootEl`, in `componentRenderUtils`. It applies the helper to `$el`, to template refs on functional components, and to compat `vnode.elm`. These are all places where the same anchor problem surfaces, so the fix is consistent rather than limited to `$el`. Patch B also resolves through `Suspense`'s `activeBranch`, which A does not, but that is an edge case beyond what the issue asks. B also starts from `i.subTree` instead of `i.vnode`, which is equivalent in practice. Tests: Patch A includes an end-to-end test in `packages/vue` that compiles the exact template from the issue (`<!-- comment --><div>`). It asserts that `childRef.value.$el` is the div and that a click listener attached via `$el` fires. That directly reproduces the user's symptom and would fail before the fix. A also covers HOC/nested chains, reactive root replacement (staying in sync after a re-render), the multiple-root fallback, functional component refs, and compat `elm`. Patch B's tests are solid unit tests using hand-built fragment blocks, covering nested chains, Suspense, and the async/mount edge cases. However, they never exercise the real compiler output, and they don't check behavior after an update. Scope and craft: A's extra coverage of functional refs and compat `elm` uses the same helper and adds little risk. B's change is tighter but adds `PatchFlags` and vnode-related imports to `componentPublicInstance` instead of keeping the logic in the render utils. Overall, A is the more thorough and better-verified fix, mainly because its integration test reproduces the issue as reported.
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
7m 59s
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
231vs 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..3f7e1e8c1 100644@@ -1,12 +1,19 @@ import {+ Fragment, createApp,+ createBlock,+ createCommentVNode, defineComponent, getCurrentInstance, h,+ nextTick, nodeOps,+ openBlock,+ ref, render, shallowReadonly, } from '@vue/runtime-test'+import { PatchFlags } from '@vue/shared' import type { ComponentInternalInstance, ComponentOptions,@@ -510,4 +517,91 @@ describe('component: proxy', () => { render(h(Comp), nodeOps.createElement('div')) expect(`Cannot mutate <script setup> binding "foo"`).toHaveBeenWarned() })++ describe('$el with root level comments (dev root fragment)', () => {+ // mimics compiled output of a template like+ // `<!-- comment --><div>...</div>` in dev mode+ const renderWithComment = (root: () => any) => {+ openBlock()+ return createBlock(+ Fragment,+ null,+ [createCommentVNode(' comment '), root()],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ }++ test('points to the single root element instead of fragment anchor', () => {+ let instanceProxy: any+ const Comp = {+ mounted() {+ instanceProxy = this+ },+ render: () => renderWithComment(() => h('div', { id: 'root' })),+ }+ const root = nodeOps.createElement('div')+ render(h(Comp), root)+ const div = root.children.find(+ (c: any) => c.type === 'element' && c.tag === 'div',+ )+ expect(div).toBeTruthy()+ expect(instanceProxy.$el).toBe(div)+ })++ test('resolves through HOC and nested dev root fragments', () => {+ let instanceProxy: any+ const Child = {+ render: () => renderWithComment(() => h('div', { id: 'child' })),+ }+ const Parent = {+ mounted() {+ instanceProxy = this+ },+ render: () => renderWithComment(() => h(Child)),+ }+ const root = nodeOps.createElement('div')+ render(h(Parent), root)+ const div = root.children.find(+ (c: any) => c.type === 'element' && c.tag === 'div',+ )+ expect(div).toBeTruthy()+ expect(instanceProxy.$el).toBe(div)+ })++ test('stays in sync when the root element is replaced', async () => {+ let instanceProxy: any+ const tag = ref('div')+ const Comp = {+ mounted() {+ instanceProxy = this+ },+ render: () => renderWithComment(() => h(tag.value)),+ }+ const root = nodeOps.createElement('div')+ render(h(Comp), root)+ expect((instanceProxy.$el as any).tag).toBe('div')++ tag.value = 'span'+ await nextTick()+ const span = root.children.find(+ (c: any) => c.type === 'element' && c.tag === 'span',+ )+ expect(span).toBeTruthy()+ expect(instanceProxy.$el).toBe(span)+ })++ test('falls back to fragment anchor with multiple real roots', () => {+ let instanceProxy: any+ const Comp = {+ mounted() {+ instanceProxy = this+ },+ render: () => [h('div'), h('span')],+ }+ const root = nodeOps.createElement('div')+ render(h(Comp), root)+ expect(instanceProxy.$el).toBe(root.children[0])+ expect((instanceProxy.$el as any).type).toBe('text')+ })+ }) })packages/runtime-core/__tests__/rendererTemplateRef.spec.tsindex 53e03c827..aaec8ccda 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,30 @@ describe('api: template refs', () => { await nextTick() expect(instanceRef.value.name).toBe('AsyncComp') })++ test('ref on functional component with root level comments', () => {+ const root = nodeOps.createElement('div')+ const el = ref<any>(null)+ // mimics dev mode compiled output of `<!-- comment --><div />`+ const Func = () => (+ openBlock(),+ createBlock(+ Fragment,+ null,+ [createCommentVNode(' comment '), h('div')],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ )+ const Comp = {+ setup() {+ return () => h(Func, { ref: el })+ },+ }+ render(h(Comp), root)+ const div = root.children.find(+ (c: any) => c.type === 'element' && c.tag === 'div',+ )+ expect(div).toBeTruthy()+ expect(el.value).toBe(div)+ }) })packages/runtime-core/src/compat/renderFn.tsindex 94c838240..db76ccba4 100644@@ -18,6 +18,7 @@ import type { InternalRenderFunction, } from '../component' import { currentRenderingInstance } from '../componentRenderContext'+import { getComponentRootEl } from '../componentRenderUtils' import { type DirectiveArguments, withDirectives } from '../directives' import { resolveDirective,@@ -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..2e4209a4d 100644@@ -7,6 +7,7 @@ import { isStatefulComponent, } from './component' import { nextTick, queueJob } from './scheduler'+import { getComponentRootEl } from './componentRenderUtils' import { type OnCleanup, type WatchOptions,@@ -363,7 +364,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..f5b64ed3e 100644@@ -311,6 +311,42 @@ const getChildRoot = (vnode: VNode): [VNode, SetRootFn] => { return [normalizeVNode(childRoot), setRoot] } +/**+ * Resolve the host element of a component vnode for user-facing access+ * (`$el`, template refs on functional components, compat `vnode.elm`).+ * In dev mode, template root level comments turn the root into a fragment,+ * whose `el` is an empty text anchor. In that case, return the element of+ * the single non-comment root instead, consistent with production builds+ * where comments are stripped.+ */+export function getComponentRootEl(vnode: VNode): VNode['el'] {+ if (__DEV__) {+ let root = vnode+ let resolved = false+ 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,+ false,+ )+ if (!singleRoot) break+ root = singleRoot+ resolved = true+ } else {+ break+ }+ }+ if (resolved) return root.el+ }+ return vnode.el+}+ export function filterSingleRoot( children: VNodeArrayChildren, recurse = true,packages/runtime-core/src/rendererTemplateRef.tsindex 737c1c8c3..bba895bf8 100644@@ -16,6 +16,7 @@ import { remove, } from '@vue/shared' import { isAsyncWrapper } from './apiAsyncComponent'+import { getComponentRootEl } from './componentRenderUtils' import { warn } from './warning' import { isRef, toRaw } from '@vue/reactivity' import { ErrorCodes, callWithErrorHandling } from './errorHandling'@@ -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..8213b75dd 100644@@ -1,9 +1,13 @@-import { ShapeFlags } from '@vue/shared'+import { PatchFlags, ShapeFlags } from '@vue/shared' import Vue from '@vue/compat' import { createComponentInstance } from '../../runtime-core/src/component' import { setCurrentRenderingInstance } from '../../runtime-core/src/componentRenderContext' import type { DirectiveBinding } from '../../runtime-core/src/directives'-import { createVNode } from '../../runtime-core/src/vnode'+import {+ Fragment,+ createCommentVNode,+ createVNode,+} from '../../runtime-core/src/vnode' import { DeprecationTypes, deprecationData,@@ -252,4 +256,29 @@ describe('compat: render function', () => { expect(vm.$el).toBeInstanceOf(HTMLDivElement) expect(vm.$el.outerHTML).toBe(`<div>hello</div>`) })++ test('vnode.elm of component with root level comments', () => {+ // mimics dev compiled output of `<!-- comment --><div class="child"/>`+ const Child = {+ render: () =>+ createVNode(+ Fragment,+ null,+ [+ createCommentVNode(' comment '),+ createVNode('div', { class: 'child' }),+ ],+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ ),+ }+ let childVNode: any+ const vm = new Vue({+ render(h: any) {+ return (childVNode = h(Child))+ },+ }).$mount()+ expect(vm.$el).toBeInstanceOf(HTMLDivElement)+ expect(vm.$el.className).toBe('child')+ expect(childVNode.elm).toBe(vm.$el)+ }) })packages/vue/__tests__/index.spec.tsindex 98f00cf28..51c444830 100644@@ -506,4 +506,30 @@ describe('compiler + runtime integration', () => { app.unmount() }) })++ // root level comments in a child template should not make+ // `$el` point to the fragment anchor+ test('$el of component with root level comments points to root element', () => {+ const container = document.createElement('div')+ const onClick = vi.fn()+ const Child = {+ template: `<!-- comment --><div class="child">Test</div>`,+ }+ const childRef = ref<any>(null)+ const App = {+ components: { Child },+ setup() {+ return { childRef }+ },+ template: `<div class="parent"><Child ref="childRef" /></div>`,+ mounted() {+ childRef.value.$el.addEventListener('click', onClick)+ },+ }+ createApp(App).mount(container)+ const childEl = container.querySelector('.child') as HTMLElement+ expect(childRef.value.$el).toBe(childEl)+ childEl.click()+ expect(onClick).toHaveBeenCalledTimes(1)+ }) })
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),