Skip to content

Commit

Permalink
feat: useReactive
Browse files Browse the repository at this point in the history
  • Loading branch information
kalu5 committed Apr 15, 2024
1 parent c991a04 commit 7baf4fb
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 1 deletion.
40 changes: 40 additions & 0 deletions __test__/useReactive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { ToRefs } from 'vue'
import { unref } from 'vue'
import { expect, it } from 'vitest'
import { useReactive } from '../libs/main'

it('useReactive obj', () => {
const [state, stateRef] = useReactive({
name: '',
age: 0,
})
expect((state.name)).toBe('')
const { setName, setAge } = stateRef as ToRefs<{
name: string
age: number
setName: (newVal: any) => void
setAge: (newVal: any) => void
}>
unref(setName)('test')
expect(state.name).toBe('test')
unref(setAge)(11)
expect(state.age).toBe(11)
})

it('useReactive object array', () => {
const [state, stateRef] = useReactive({
name: [{ fist: 'k', last: 'l' }],
age: ['1'],
})
expect((state.name)).toEqual([{ fist: 'k', last: 'l' }])
const { setName, setAge } = stateRef as ToRefs<{
name: { fist: string, last: string }[]
age: string[]
setName: (newVal: any) => void
setAge: (newVal: any) => void
}>
unref(setName)([{ fist: 'kk', last: 'll' }])
expect(state.name).toEqual([{ fist: 'kk', last: 'll' }])
unref(setAge)(['122', '233'])
expect(state.age).toEqual(['122', '233'])
})
2 changes: 2 additions & 0 deletions libs/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import useState from './useState'
import useReducer from './useReducer'
import useReactive from './useReactive'

export {
useState,
useReducer,
useReactive,
}
15 changes: 15 additions & 0 deletions libs/hooks/useReactive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { reactive, toRefs } from 'vue'
import { isFunc } from '../utils/index'

export default function useReactive<T extends Record<string, any> >(init: T) {
const state = reactive<T>(init)
Object.keys(init).forEach((key) => {
state[`set${key.slice(0, 1).toUpperCase()}${key.slice(1)}`] = function <U> (newState: U) {
state[key] = isFunc<U>(newState) ? (newState as unknown as Function)(state[key]) : newState
}
})
return [
state,
toRefs(state),
]
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@kalu5/vue3-hooks",
"type": "module",
"version": "1.0.1",
"version": "1.0.2",
"private": false,
"description": "This is vue3 hooks utils",
"author": "lujialong",
Expand Down

0 comments on commit 7baf4fb

Please sign in to comment.