Skip to content

Commit

Permalink
feat(url): support using ref as state (#430)
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Jan 5, 2024
1 parent 71e341b commit 57ef0af
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions lib/composables/Url.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import isEqual from 'lodash-es/isEqual'
import isPlainObject from 'lodash-es/isPlainObject'
import { watch } from 'vue'
import { type MaybeRef, unref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export interface UseUrlQuerySyncOptions {
Expand All @@ -9,20 +9,25 @@ export interface UseUrlQuerySyncOptions {
}

export function useUrlQuerySync(
state: Record<string, any>,
state: MaybeRef<Record<string, any>>,
{ casts = {}, exclude }: UseUrlQuerySyncOptions = {}
): void {
const router = useRouter()
const route = useRoute()

const flattenInitialState = flattenObject(JSON.parse(JSON.stringify(state)))
const flattenInitialState = flattenObject(
JSON.parse(JSON.stringify(unref(state)))
)

setStateFromQuery()

watch(() => state, setQueryFromState, { deep: true, immediate: true })
watch(() => unref(state), setQueryFromState, {
deep: true,
immediate: true
})

function setStateFromQuery() {
const flattenState = flattenObject(state)
const flattenState = flattenObject(unref(state))
const flattenQuery = flattenObject(route.query)

Object.keys(flattenQuery).forEach((key) => {
Expand All @@ -39,11 +44,11 @@ export function useUrlQuerySync(
flattenState[key] = cast ? cast(value) : value
})

deepAssign(state, unflattenObject(flattenState))
deepAssign(unref(state), unflattenObject(flattenState))
}

async function setQueryFromState() {
const flattenState = flattenObject(state)
const flattenState = flattenObject(unref(state))
const flattenQuery = flattenObject(route.query)

Object.keys(flattenState).forEach((key) => {
Expand Down Expand Up @@ -110,7 +115,11 @@ function deepAssign(target: Record<string, any>, source: Record<string, any>) {
}
}

function deepAssignBase(dest: Record<string, any>, src: Record<string, any>, key: string | number) {
function deepAssignBase(
dest: Record<string, any>,
src: Record<string, any>,
key: string | number
) {
if (typeof src[key] === 'object' && src[key] !== null) {
deepAssign(dest[key], src[key])
} else {
Expand Down

0 comments on commit 57ef0af

Please sign in to comment.