Backtestsvuerun-20261002-115633#12680
$el of templateRef points to comment VNode instead of first real child of component
The merged fix was judged better than our patch.
No judgment was produced for this ticket. It counts as an error in the run total.
Solve
9m 3s
Wall-clock time in the container
Full test suite
1 new failure
3,695 passed · 6 skipped · 3,702 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
116vs 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..a768fa303 100644@@ -1,12 +1,19 @@ import {+ Fragment, createApp,+ createBlock,+ createCommentVNode, defineComponent, getCurrentInstance, h, nodeOps,+ openBlock,+ ref, render,+ serializeInner, shallowReadonly, } from '@vue/runtime-test'+import { PatchFlags } from '@vue/shared' import type { ComponentInternalInstance, ComponentOptions,@@ -510,4 +517,82 @@ describe('component: proxy', () => { render(h(Comp), nodeOps.createElement('div')) expect(`Cannot mutate <script setup> binding "foo"`).toHaveBeenWarned() })++ // dev root fragment (template root with comments)+ describe('$el with root level comments', () => {+ const devRootFragment = (children: any[]) => (+ openBlock(),+ createBlock(+ Fragment,+ null,+ children,+ PatchFlags.STABLE_FRAGMENT | PatchFlags.DEV_ROOT_FRAGMENT,+ )+ )++ test('should point to the single non-comment root element', () => {+ const Child = {+ render: () =>+ devRootFragment([createCommentVNode('comment'), h('div', 'test')]),+ }+ const childRef = ref<any>(null)+ const Parent = {+ render: () => h(Child, { ref: childRef }),+ }+ const root = nodeOps.createElement('div')+ render(h(Parent), root)+ expect(serializeInner(root)).toBe(`<!--comment--><div>test</div>`)+ const el = childRef.value.$el+ expect(el.type).toBe('element')+ expect(el.tag).toBe('div')+ expect(el).toBe(root.children.find((n: any) => n.tag === 'div'))+ })++ test('nested dev root fragments', () => {+ const Inner = {+ render: () =>+ devRootFragment([+ createCommentVNode('a'),+ devRootFragment([createCommentVNode('b'), h('span')]),+ ]),+ }+ const Child = {+ render: () => devRootFragment([createCommentVNode('c'), h(Inner)]),+ }+ const childRef = ref<any>(null)+ const root = nodeOps.createElement('div')+ render(h(() => h(Child, { ref: childRef })), root)+ expect(serializeInner(root)).toBe(`<!--c--><!--a--><!--b--><span></span>`)+ expect(childRef.value.$el.tag).toBe('span')+ })++ test('HOC wrapping a component with a dev root fragment', () => {+ const Inner = {+ render: () =>+ devRootFragment([createCommentVNode('comment'), h('div')]),+ }+ const Wrapper = {+ render: () => h(Inner),+ }+ const wrapperRef = ref<any>(null)+ const root = nodeOps.createElement('div')+ render(h(() => h(Wrapper, { ref: wrapperRef })), root)+ expect(wrapperRef.value.$el.tag).toBe('div')+ })++ test('should keep v-if placeholder comment as $el', () => {+ const Child = {+ render: () =>+ devRootFragment([+ createCommentVNode('comment'),+ createCommentVNode('v-if', true),+ ]),+ }+ const childRef = ref<any>(null)+ const root = nodeOps.createElement('div')+ render(h(() => h(Child, { ref: childRef })), root)+ expect(childRef.value.$el.type).toBe('comment')+ expect(childRef.value.$el.text).toBe('v-if')+ })+ }) })packages/runtime-core/src/componentPublicInstance.tsindex 7a8af5871..3ef8b148d 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 { getDevRootEl, 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 => (__DEV__ ? getDevRootEl(i) : 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/src/componentRenderUtils.tsindex be58e5b0a..e98b0ee56 100644@@ -496,3 +496,30 @@ export function updateHOCHostEl( suspense.vnode.el = el } }++/**+ * dev only+ * In dev mode, template root level comments are rendered, which turns the+ * template into a fragment root whose `el` is the fragment's start anchor.+ * Resolve the single non-comment root's element instead so `$el` matches+ * production behavior (where root comments are stripped).+ */+export function getDevRootEl(+ instance: ComponentInternalInstance,+): VNode['el'] {+ const subTree = instance.subTree+ if (+ subTree &&+ subTree.patchFlag > 0 &&+ subTree.patchFlag & PatchFlags.DEV_ROOT_FRAGMENT+ ) {+ const root = filterSingleRoot(subTree.children as VNodeArrayChildren)+ if (root) {+ return root.component ? getDevRootEl(root.component) : root.el+ }+ } else if (subTree && subTree.component) {+ // HOC: the child component's root may itself be a dev root fragment+ return getDevRootEl(subTree.component)+ }+ return instance.vnode.el+}
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),