Ver Fonte

dx(useTemplateRef): warn when declaring with the same key (#11462)

Tycho há 1 ano atrás
pai
commit
55acabe88c

+ 14 - 0
packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts

@@ -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()
+  })
 })

+ 15 - 5
packages/runtime-core/src/helpers/useTemplateRef.ts

@@ -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 ` +