]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
dx(useTemplateRef): warn when declaring with the same key (#11462)
authorTycho <jh.leong@outlook.com>
Fri, 2 Aug 2024 05:18:58 +0000 (13:18 +0800)
committerGitHub <noreply@github.com>
Fri, 2 Aug 2024 05:18:58 +0000 (13:18 +0800)
packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts
packages/runtime-core/src/helpers/useTemplateRef.ts

index fa69adccb2ea132a0590f95a5f0610e8369344a6..9e4137da80fc2d380ca74b177a4f979f1cae3fd4 100644 (file)
@@ -68,4 +68,18 @@ describe('useTemplateRef', () => {
     expect(t2!.value).toBe(root.children[0])
     expect(t1!.value).toBe(null)
   })
+
+  test('should warn on duplicate useTemplateRef', () => {
+    const root = nodeOps.createElement('div')
+    render(
+      h(() => {
+        useTemplateRef('foo')
+        useTemplateRef('foo')
+        return ''
+      }),
+      root,
+    )
+
+    expect(`useTemplateRef('foo') already exists.`).toHaveBeenWarned()
+  })
 })
index 12663962a8e4c340c6a512386e234ca1e4239aa7..58c109a9246962c3baaf057a2f6268bdb9da4434 100644 (file)
@@ -10,11 +10,21 @@ export function useTemplateRef<T = unknown, Keys extends string = string>(
   const r = shallowRef(null)
   if (i) {
     const refs = i.refs === EMPTY_OBJ ? (i.refs = {}) : i.refs
-    Object.defineProperty(refs, key, {
-      enumerable: true,
-      get: () => r.value,
-      set: val => (r.value = val),
-    })
+
+    let desc: PropertyDescriptor | undefined
+    if (
+      __DEV__ &&
+      (desc = Object.getOwnPropertyDescriptor(refs, key)) &&
+      !desc.configurable
+    ) {
+      warn(`useTemplateRef('${key}') already exists.`)
+    } else {
+      Object.defineProperty(refs, key, {
+        enumerable: true,
+        get: () => r.value,
+        set: val => (r.value = val),
+      })
+    }
   } else if (__DEV__) {
     warn(
       `useTemplateRef() is called when there is no active component ` +