Skip to content

Commit bc63df0

Browse files
committed
fix(useTemplateRef): fix readonly warning when useTemplateRef has same variable name as template ref
close #11795 close #11802 close #11804
1 parent 7518bc1 commit bc63df0

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts

+21
Original file line numberDiff line numberDiff line change
@@ -82,4 +82,25 @@ describe('useTemplateRef', () => {
8282

8383
expect(`useTemplateRef('foo') already exists.`).toHaveBeenWarned()
8484
})
85+
86+
// #11795
87+
test('should work when variable name is same as key', () => {
88+
let tRef
89+
const key = 'refKey'
90+
const Comp = {
91+
setup() {
92+
tRef = useTemplateRef(key)
93+
return {
94+
[key]: tRef,
95+
}
96+
},
97+
render() {
98+
return h('div', { ref: key })
99+
},
100+
}
101+
const root = nodeOps.createElement('div')
102+
render(h(Comp), root)
103+
104+
expect('target is readonly').not.toHaveBeenWarned()
105+
})
85106
})

packages/runtime-core/src/rendererTemplateRef.ts

+11-4
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,18 @@ export function setRef(
6363
const oldRef = oldRawRef && (oldRawRef as VNodeNormalizedRefAtom).r
6464
const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs
6565
const setupState = owner.setupState
66+
const canSetSetupRef =
67+
setupState === EMPTY_OBJ
68+
? () => false
69+
: (key: string) =>
70+
hasOwn(setupState, key) &&
71+
!(Object.getOwnPropertyDescriptor(refs, key) || EMPTY_OBJ).get
6672

6773
// dynamic ref changed. unset old ref
6874
if (oldRef != null && oldRef !== ref) {
6975
if (isString(oldRef)) {
7076
refs[oldRef] = null
71-
if (hasOwn(setupState, oldRef)) {
77+
if (canSetSetupRef(oldRef)) {
7278
setupState[oldRef] = null
7379
}
7480
} else if (isRef(oldRef)) {
@@ -81,11 +87,12 @@ export function setRef(
8187
} else {
8288
const _isString = isString(ref)
8389
const _isRef = isRef(ref)
90+
8491
if (_isString || _isRef) {
8592
const doSet = () => {
8693
if (rawRef.f) {
8794
const existing = _isString
88-
? hasOwn(setupState, ref)
95+
? canSetSetupRef(ref)
8996
? setupState[ref]
9097
: refs[ref]
9198
: ref.value
@@ -95,7 +102,7 @@ export function setRef(
95102
if (!isArray(existing)) {
96103
if (_isString) {
97104
refs[ref] = [refValue]
98-
if (hasOwn(setupState, ref)) {
105+
if (canSetSetupRef(ref)) {
99106
setupState[ref] = refs[ref]
100107
}
101108
} else {
@@ -108,7 +115,7 @@ export function setRef(
108115
}
109116
} else if (_isString) {
110117
refs[ref] = value
111-
if (hasOwn(setupState, ref)) {
118+
if (canSetSetupRef(ref)) {
112119
setupState[ref] = value
113120
}
114121
} else if (_isRef) {

0 commit comments

Comments
 (0)