Skip to content

Commit 0126cff

Browse files
authoredJun 23, 2024··
fix(shared): unwrap refs in toDisplayString (#7306)
close #5578 close #5593 close #11199 close #11201
1 parent 582cd2e commit 0126cff

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed
 

‎packages/shared/__tests__/toDisplayString.spec.ts

+16
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,28 @@ describe('toDisplayString', () => {
1111
})
1212

1313
test('primitive values', () => {
14+
expect(toDisplayString(0)).toBe('0')
1415
expect(toDisplayString(1)).toBe('1')
16+
expect(toDisplayString(NaN)).toBe('NaN')
1517
expect(toDisplayString(true)).toBe('true')
1618
expect(toDisplayString(false)).toBe('false')
1719
expect(toDisplayString('hello')).toBe('hello')
1820
})
1921

22+
test('primitive values in refs', () => {
23+
expect(toDisplayString(ref(0))).toBe('0')
24+
expect(toDisplayString(ref(1))).toBe('1')
25+
expect(toDisplayString(ref(NaN))).toBe('NaN')
26+
expect(toDisplayString(ref(true))).toBe('true')
27+
expect(toDisplayString(ref(false))).toBe('false')
28+
expect(toDisplayString(ref('hello'))).toBe('hello')
29+
})
30+
31+
test('symbol values', () => {
32+
expect(toDisplayString(Symbol('hello'))).toBe('Symbol(hello)')
33+
expect(toDisplayString(ref(Symbol('hello')))).toBe('Symbol(hello)')
34+
})
35+
2036
test('Object and Arrays', () => {
2137
const obj = { foo: 123 }
2238
expect(toDisplayString(obj)).toBe(JSON.stringify(obj, null, 2))

‎packages/shared/src/toDisplayString.ts

+10-4
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,11 @@ import {
1010
objectToString,
1111
} from './general'
1212

13+
// can't use isRef here since @vue/shared has no deps
14+
const isRef = (val: any): val is { value: unknown } => {
15+
return !!(val && val.__v_isRef === true)
16+
}
17+
1318
/**
1419
* For converting {{ interpolation }} values to displayed strings.
1520
* @private
@@ -22,13 +27,14 @@ export const toDisplayString = (val: unknown): string => {
2227
: isArray(val) ||
2328
(isObject(val) &&
2429
(val.toString === objectToString || !isFunction(val.toString)))
25-
? JSON.stringify(val, replacer, 2)
30+
? isRef(val)
31+
? toDisplayString(val.value)
32+
: JSON.stringify(val, replacer, 2)
2633
: String(val)
2734
}
2835

29-
const replacer = (_key: string, val: any): any => {
30-
// can't use isRef here since @vue/shared has no deps
31-
if (val && val.__v_isRef) {
36+
const replacer = (_key: string, val: unknown): any => {
37+
if (isRef(val)) {
3238
return replacer(_key, val.value)
3339
} else if (isMap(val)) {
3440
return {

0 commit comments

Comments
 (0)
Please sign in to comment.