Skip to content

Commit

Permalink
feat: add mutate method
Browse files Browse the repository at this point in the history
  • Loading branch information
sxzz committed Jan 27, 2023
1 parent 487340b commit 83428f0
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
13 changes: 10 additions & 3 deletions src/index.ts
@@ -1,5 +1,6 @@
import {
isRef,
triggerRef,
computed as vueComputed,
customRef as vueCustomRef,
readonly as vueReadonly,
Expand Down Expand Up @@ -40,12 +41,18 @@ function toFunctional(raw: any, readonly: boolean): any {
])
)

const set = (value: any) => (raw.value = value)
const mutate = (mutator: (value: any) => any) => {
mutator(raw.value)
triggerRef(raw)
}

return new Proxy(fn, {
...handlers,
get(target, key) {
if (!readonly && key === 'set') {
return (value: any) => (raw.value = value)
} else if (key === '__raw_ref') {
if (!readonly && key === 'set') return set
else if (!readonly && key === 'mutate') return mutate
else if (key === '__raw_ref') {
return toRawRef(raw)
} else {
return Reflect.get(raw, key, raw)
Expand Down
22 changes: 22 additions & 0 deletions tests/index.test.ts
Expand Up @@ -5,6 +5,7 @@ import {
customRef,
isReadonly,
isRef,
nextTick,
reactive,
readonly,
ref,
Expand Down Expand Up @@ -234,3 +235,24 @@ test('export types', () => {
keyof typeof vueReactivityType
>()
})

test('mutate', async () => {
const fn = vi.fn()

const foo = ref({ foo: 'foo', nested: { count: 1 } })
watch(
() => foo().nested.count,
() => fn()
)

foo.mutate((foo) => {
foo.foo = 'bar'
foo.nested.count++
})

await nextTick()

expect(foo().foo).toBe('bar')
expect(foo().nested.count).toBe(2)
expect(fn).toBeCalledTimes(1)
})
7 changes: 6 additions & 1 deletion types.d.ts
Expand Up @@ -69,7 +69,12 @@ export declare type FunctionalRef<
Writable extends boolean = boolean
> = {
(): T
} & (Writable extends true ? { set: (value: T) => void } : {})
} & (Writable extends true
? {
set: (value: T) => void
mutate: (mutator: (value: T) => void) => void
}
: {})

export declare interface ComputedRef<T = any> extends WritableComputedRef<T> {
set: never
Expand Down

0 comments on commit 83428f0

Please sign in to comment.