forked from mengyxu/noob-components
3 changed files with 74 additions and 0 deletions
@ -0,0 +1,49 @@
@@ -0,0 +1,49 @@
|
||||
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 } |
||||
); |
||||
} |
||||
} |
||||
Loading…
Reference in new issue