Backtestsvuerun-20261003-231210#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 A = our agent, Patch B = the merged fix.
Both patches find the same root cause. In dev builds a template with a root-level comment plus one element compiles to a fragment flagged DEV_ROOT_FRAGMENT. `$el` then returns `i.vnode.el`, which is the fragment's anchor node, not the real element. Both fix this by using `filterSingleRoot` on the fragment's children to find the single real root. Patch A's `getRootEl` recurses through `subTree.component` even when no dev root fragment is present. For an ordinary wrapper/HOC this usually gives the same element that `i.vnode.el` already holds, since the host el is propagated upward. Still, it changes the lookup path for every `$el` access, including production, for no benefit there. It also does not see through a Suspense root, so a component that renders `<Suspense>` around a comment-plus-element child still returns the anchor. Patch B's `resolveDevRootEl` loops through component subTrees, Suspense `activeBranch`, and nested dev root fragments. It returns a different element only if it actually found a dev root fragment; otherwise it falls back to `i.vnode.el`. This keeps the existing semantics for every other root chain. B also guards the logic behind `__DEV__`, which is the only mode where DEV_ROOT_FRAGMENT exists, so production behaviour and cost are unchanged. On tests, B adds targeted runtime-core tests built with explicit patch flags. They cover: - the direct case - a wrapper component - nested fragments across component boundaries - a Suspense root - safety when `$el` is read while the child is still mounting - preserving the unresolved async-root value All of these would fail before the fix where relevant. A's integration tests via the full compiler are realistic and cover v-if updates, keyed re-creation and the multi-root fallback, which is good. They do not cover Suspense, though. Overall B is more conservative, handles more of the root-chain shapes, and has broader edge-case tests, so it is the better 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
9m 49s
Wall-clock time in the container
Full test suite
No new failures
3,697 passed · 6 skipped · 3,703 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
130vs 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/src/componentPublicInstance.tsindex 7a8af5871..5b2e98eee 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`@@ -358,12 +360,36 @@ const getPublicInstance = ( return getPublicInstance(i.parent) } +/**+ * Resolve the component's root element for `$el`. When the template root+ * contains comments alongside a single element (dev-compiled templates keep+ * comments), the subTree is a fragment whose el is an anchor node, so locate+ * the single real root instead. A root that is itself a component (e.g. a+ * wrapper / HOC) is resolved recursively.+ */+const getRootEl = (i: ComponentInternalInstance): any => {+ const subTree = i.subTree+ if (!subTree) return i.vnode.el+ if (+ subTree.patchFlag > 0 &&+ subTree.patchFlag & PatchFlags.DEV_ROOT_FRAGMENT+ ) {+ const root = filterSingleRoot(subTree.children as VNodeArrayChildren)+ if (root) {+ return root.component ? getRootEl(root.component) : root.el+ }+ } else if (subTree.component) {+ return getRootEl(subTree.component)+ }+ return i.vnode.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: getRootEl, $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..1a1a0bfa3 100644@@ -507,3 +507,103 @@ describe('compiler + runtime integration', () => { }) }) })++describe('$el with root-level comments', () => {+ it('should point to the single root element instead of the fragment anchor', async () => {+ const container = document.createElement('div')+ const Child = {+ template: `<!-- comment --><div class="child">Test</div>`,+ }+ const childRef = ref<any>(null)+ const toggle = ref(true)+ const App = {+ components: { Child },+ setup: () => ({ childRef, toggle }),+ template: `<div class="parent"><Child ref="childRef" :key="String(toggle)" /></div>`,+ }+ createApp(App).mount(container)+ const el = childRef.value.$el+ expect(el).toBe(container.querySelector('.child'))+ expect(el.tagName).toBe('DIV')++ // remains correct after the child is re-created+ toggle.value = false+ await nextTick()+ expect(childRef.value.$el).toBe(container.querySelector('.child'))+ })++ it('should resolve through nested components with root-level comments', () => {+ const container = document.createElement('div')+ const GrandChild = {+ template: `<!-- a --><span class="grand">hi</span><!-- b -->`,+ }+ const childRef = ref<any>(null)+ const App = {+ components: {+ Child: {+ components: { GrandChild },+ template: `<!-- c --><GrandChild />`,+ },+ },+ setup: () => ({ childRef }),+ template: `<Child ref="childRef" />`,+ }+ createApp(App).mount(container)+ expect(childRef.value.$el).toBe(container.querySelector('.grand'))+ })++ it('should resolve through a wrapper component without comments', () => {+ const container = document.createElement('div')+ const Inner = {+ template: `<!-- c --><div class="inner">hi</div>`,+ }+ const wrapperRef = ref<any>(null)+ const App = {+ components: {+ Wrapper: {+ components: { Inner },+ template: `<Inner />`,+ },+ },+ setup: () => ({ wrapperRef }),+ template: `<Wrapper ref="wrapperRef" />`,+ }+ createApp(App).mount(container)+ expect(wrapperRef.value.$el).toBe(container.querySelector('.inner'))+ })++ it('should follow v-if root updates', async () => {+ const container = document.createElement('div')+ const ok = ref(true)+ const childRef = ref<any>(null)+ const App = {+ components: {+ Child: {+ setup: () => ({ ok }),+ template: `<!-- c --><div v-if="ok" class="a" /><p v-else class="b" />`,+ },+ },+ setup: () => ({ childRef }),+ template: `<Child ref="childRef" />`,+ }+ createApp(App).mount(container)+ expect(childRef.value.$el).toBe(container.querySelector('.a'))+ ok.value = false+ await nextTick()+ expect(childRef.value.$el).toBe(container.querySelector('.b'))+ })++ it('should keep the fragment anchor when there are multiple real roots', () => {+ const container = document.createElement('div')+ const childRef = ref<any>(null)+ const App = {+ components: {+ Child: { template: `<!-- c --><div /><span />` },+ },+ setup: () => ({ childRef }),+ template: `<Child ref="childRef" />`,+ }+ createApp(App).mount(container)+ expect(childRef.value.$el.nodeType).toBe(Node.TEXT_NODE)+ })+})
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),