Skip to content

Commit

Permalink
fix: error in url state modification caused by an immutable variable
Browse files Browse the repository at this point in the history
  • Loading branch information
NelsonYong committed Jun 9, 2023
1 parent 5c20187 commit 10e7c74
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions packages/hooks/src/useUrlState/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
/**
* Will be deprecated in version 1.7.6
*/
import qs from 'qs'
import { Ref, ref, watch } from 'vue'
import { Ref, ref, watch, watchEffect } from 'vue'
import { useLocalStorageState } from '../index'
import { isFunction } from '../utils'

Expand Down Expand Up @@ -63,12 +66,19 @@ function useUrlState<S extends UrlState = Partial<UrlState>>(

const defaultState = (isFunction(initialState) ? initialState() : initialState) ?? ({} as S)

const state = (localStorageKey
const state_ = (localStorageKey
? useLocalStorageState(localStorageKey, {
defaultValue: defaultState,
})[0]
: ref(defaultState)) as Ref<S>

const state = ref<S>() as Ref<S>

watchEffect(() => {
state.value = state_.value
})


// 初始状态 url > localstorage
if (paramsStr) {
try {
Expand All @@ -87,20 +97,24 @@ function useUrlState<S extends UrlState = Partial<UrlState>>(
// 去掉多余的key
if (initialState && Object.keys(initialState).length) {
const newState = { ...initialState } as any
for (const key in newState) {
if (key in state.value) {
newState[key] = state.value[key]
if (state.value)
for (const key in newState) {
if (key in state.value) {
newState[key] = state.value[key]
}
}
}
state.value = newState
}

// 把params写到url
watch(
state,
() => {
const newParamsStr = encodeParams(state.value)
routerPushFn(`${path}?${newParamsStr}`)
if (state.value) {
const newParamsStr = encodeParams(state.value)
routerPushFn(`${path}?${newParamsStr}`)
}

},
{
deep: true,
Expand All @@ -111,4 +125,4 @@ function useUrlState<S extends UrlState = Partial<UrlState>>(
return state
}

export default useUrlState
export default useUrlState

0 comments on commit 10e7c74

Please sign in to comment.