Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions packages/shared/__tests__/toDisplayString.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,28 @@ describe('toDisplayString', () => {
})

test('primitive values', () => {
expect(toDisplayString(0)).toBe('0')
expect(toDisplayString(1)).toBe('1')
expect(toDisplayString(NaN)).toBe('NaN')
expect(toDisplayString(true)).toBe('true')
expect(toDisplayString(false)).toBe('false')
expect(toDisplayString('hello')).toBe('hello')
})

test('primitive values in refs', () => {
expect(toDisplayString(ref(0))).toBe('0')
expect(toDisplayString(ref(1))).toBe('1')
expect(toDisplayString(ref(NaN))).toBe('NaN')
expect(toDisplayString(ref(true))).toBe('true')
expect(toDisplayString(ref(false))).toBe('false')
expect(toDisplayString(ref('hello'))).toBe('hello')
})

test('symbol values', () => {
expect(toDisplayString(Symbol('hello'))).toBe('Symbol(hello)')
expect(toDisplayString(ref(Symbol('hello')))).toBe('Symbol(hello)')
})

test('Object and Arrays', () => {
const obj = { foo: 123 }
expect(toDisplayString(obj)).toBe(JSON.stringify(obj, null, 2))
Expand Down
14 changes: 10 additions & 4 deletions packages/shared/src/toDisplayString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ import {
objectToString,
} from './general'

// can't use isRef here since @vue/shared has no deps
const isRef = (val: any): val is { value: unknown } => {
return !!(val && val.__v_isRef === true)
}

/**
* For converting {{ interpolation }} values to displayed strings.
* @private
Expand All @@ -22,13 +27,14 @@ export const toDisplayString = (val: unknown): string => {
: isArray(val) ||
(isObject(val) &&
(val.toString === objectToString || !isFunction(val.toString)))
? JSON.stringify(val, replacer, 2)
? isRef(val)
? toDisplayString(val.value)
: JSON.stringify(val, replacer, 2)
: String(val)
}

const replacer = (_key: string, val: any): any => {
// can't use isRef here since @vue/shared has no deps
if (val && val.__v_isRef) {
const replacer = (_key: string, val: unknown): any => {
if (isRef(val)) {
return replacer(_key, val.value)
} else if (isMap(val)) {
return {
Expand Down