forked from mengyxu/noob-components
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.2 KiB
49 lines
1.2 KiB
import { watch } from "vue"; |
|
import { useRoute } from "vue-router"; |
|
import { useStore } from "vuex"; |
|
|
|
export function useRefreshFlags( |
|
flags: string[], |
|
cb: () => void | Promise<void>, |
|
match: "any" | "all" = "any", |
|
token?: string |
|
) { |
|
const { state, dispatch } = useStore(); |
|
|
|
if (!token) { |
|
const route = useRoute(); |
|
token = route.path; |
|
} |
|
|
|
const flagSet = new Set(flags); |
|
|
|
let test; |
|
if (match === "any") { |
|
test = () => { |
|
const inter = flagSet.intersection(state.refreshFlags); |
|
return inter.size > 0 && Iterator.from(inter).some((flag) => !state.refreshFlags.get(flag)?.has(token)); |
|
}; |
|
} else if (match === "all") { |
|
test = () => { |
|
const isSubset = flagSet.isSubsetOf(state.refreshFlags); |
|
return isSubset && !Iterator.from(flagSet).some((flag) => state.refreshFlags.get(flag)?.has(token)); |
|
}; |
|
} |
|
|
|
if (test) { |
|
watch( |
|
() => { |
|
// Explicitly access state.refreshFlags to ensure reactive tracking |
|
const _ = state.refreshFlags; |
|
return test(); |
|
}, |
|
async (value, oldValue) => { |
|
if (value) { |
|
await cb(); |
|
await dispatch("unsetRefreshFlag", { flags, token }); |
|
} |
|
}, |
|
{ immediate: true } |
|
); |
|
} |
|
}
|
|
|