Skip to content

Commit

Permalink
feat(useToString): new function
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Aug 4, 2022
1 parent f69a36d commit 2b869ad
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
18 changes: 18 additions & 0 deletions packages/shared/useToString/index.md
@@ -0,0 +1,18 @@
---
category: Utilities
---

# useToString

Reactively convert a ref to string.

## Usage

```ts
import { useToString } from '@vueuse/core'

const number = ref(3.14)
const str = useToString(number)

str.value // '3.14'
```
19 changes: 19 additions & 0 deletions packages/shared/useToString/index.test.ts
@@ -0,0 +1,19 @@
import { ref } from 'vue-demi'
import { useToString } from '.'

describe('useToString', () => {
it('default', () => {
const value = ref<any>(123.345)
const str = useToString(value)

expect(str.value).toBe('123.345')

value.value = 'hi'

expect(str.value).toBe('hi')

value.value = { foo: 'hi' }

expect(str.value).toBe('[object Object]')
})
})
15 changes: 15 additions & 0 deletions packages/shared/useToString/index.ts
@@ -0,0 +1,15 @@
import type { ComputedRef } from 'vue-demi'
import { computed } from 'vue-demi'
import { resolveUnref } from '../resolveUnref'
import type { MaybeComputedRef } from '../utils'

/**
* Reactively convert a ref to string.
*
* @see https://vueuse.org/useToString
*/
export function useToString(
value: MaybeComputedRef<unknown>,
): ComputedRef<string> {
return computed(() => `${resolveUnref(value)}`)
}

0 comments on commit 2b869ad

Please sign in to comment.