Skip to content

Commit

Permalink
feat: unwrap refs in toDisplayString
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Jul 27, 2021
1 parent ee4cbae commit f994b97
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
12 changes: 12 additions & 0 deletions packages/shared/__tests__/toDisplayString.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { computed, ref } from '@vue/reactivity'
import { toDisplayString } from '../src'

describe('toDisplayString', () => {
Expand All @@ -20,6 +21,17 @@ describe('toDisplayString', () => {
expect(toDisplayString(arr)).toBe(JSON.stringify(arr, null, 2))
})

test('refs', () => {
const n = ref(1)
const np = computed(() => n.value + 1)
expect(
toDisplayString({
n,
np
})
).toBe(JSON.stringify({ n: 1, np: 2 }, null, 2))
})

test('native objects', () => {
const div = document.createElement('div')
expect(toDisplayString(div)).toBe(`"[object HTMLDivElement]"`)
Expand Down
7 changes: 5 additions & 2 deletions packages/shared/src/toDisplayString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ export const toDisplayString = (val: unknown): string => {
: String(val)
}

const replacer = (_key: string, val: any) => {
if (isMap(val)) {
const replacer = (_key: string, val: any): any => {
// can't use isRef here since @vue/shared has no deps
if (val && val.__v_isRef) {
return replacer(_key, val.value)
} else if (isMap(val)) {
return {
[`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
;(entries as any)[`${key} =>`] = val
Expand Down

0 comments on commit f994b97

Please sign in to comment.