Skip to content

Commit

Permalink
feat(reactiveComputed): new function
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Feb 26, 2022
1 parent e79d731 commit fcfec1c
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/shared/reactiveComputed/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
category: Utilities
---

# reactiveComputed

Computed reactive object. Instead of returning a ref that `computed` does, `reactiveComputed` returns a reactive object.

## Usage

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

const state = reactiveComputed(() => {
return {
foo: 'bar',
bar: 'baz'
}
})

state.bar // 'baz'
```
54 changes: 54 additions & 0 deletions packages/shared/reactiveComputed/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { nextTick, ref, watch, watchEffect } from 'vue-demi'
import { reactiveComputed } from '.'

describe('reactiveComputed', () => {
it('should work', () => {
const count = ref(0)

const state = reactiveComputed(() => {
return {
count: count.value,
}
})

expect(state.count).toBe(0)

count.value++

expect(state.count).toBe(1)
})

it('should work with dynamic props', async() => {
const foo = ref(false)

const state = reactiveComputed(() => {
return foo.value
? { foo: true, type: 'foo' }
: { bar: true, type: 'bar' }
})

let dummy = 0
let type

watch(state, () => {
dummy += 1
})
watchEffect(() => {
type = state.type
})

expect(state.foo).toBe(undefined)
expect(state.bar).toBe(true)
expect(type).toBe('bar')

foo.value = true

expect(state.foo).toBe(true)
expect(state.bar).toBe(undefined)

await nextTick()

expect(dummy).toBe(1)
expect(type).toBe('foo')
})
})
9 changes: 9 additions & 0 deletions packages/shared/reactiveComputed/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { computed } from 'vue-demi'
import { toReactive } from '../toReactive'

/**
* Computed reactive object.
*/
export function reactiveComputed<T extends {}>(fn: () => T): Readonly<T> {
return toReactive(computed(() => fn()))
}

0 comments on commit fcfec1c

Please sign in to comment.