feat: unwrap refs in toDisplayString

This commit is contained in:
Evan You 2021-07-27 18:34:15 -04:00
parent ee4cbaeec9
commit f994b974c0
2 changed files with 17 additions and 2 deletions

View File

@ -1,3 +1,4 @@
import { computed, ref } from '@vue/reactivity'
import { toDisplayString } from '../src' import { toDisplayString } from '../src'
describe('toDisplayString', () => { describe('toDisplayString', () => {
@ -20,6 +21,17 @@ describe('toDisplayString', () => {
expect(toDisplayString(arr)).toBe(JSON.stringify(arr, null, 2)) 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', () => { test('native objects', () => {
const div = document.createElement('div') const div = document.createElement('div')
expect(toDisplayString(div)).toBe(`"[object HTMLDivElement]"`) expect(toDisplayString(div)).toBe(`"[object HTMLDivElement]"`)

View File

@ -12,8 +12,11 @@ export const toDisplayString = (val: unknown): string => {
: String(val) : String(val)
} }
const replacer = (_key: string, val: any) => { const replacer = (_key: string, val: any): any => {
if (isMap(val)) { // 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 { return {
[`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => { [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
;(entries as any)[`${key} =>`] = val ;(entries as any)[`${key} =>`] = val