useRoute.ts 860 B

1234567891011121314151617181920212223242526272829303132333435
  1. // hooks/useRoute.ts
  2. import { reactive } from 'vue'
  3. const routeState = reactive({
  4. path: '',
  5. query: {} as Record<string, any>
  6. })
  7. function isSameQuery(a: Record<string, any>, b: Record<string, any>) {
  8. const aKeys = Object.keys(a || {})
  9. const bKeys = Object.keys(b || {})
  10. if (aKeys.length !== bKeys.length) return false
  11. return aKeys.every((key) => String(a[key]) === String(b[key]))
  12. }
  13. export function updateRoute() {
  14. const pages = getCurrentPages()
  15. const current = pages[pages.length - 1]
  16. if (current) {
  17. const nextPath = '/' + (current.route || '')
  18. const nextQuery = { ...(current.options || {}) }
  19. if (routeState.path === nextPath && isSameQuery(routeState.query, nextQuery)) {
  20. return
  21. }
  22. routeState.path = nextPath
  23. routeState.query = nextQuery
  24. }
  25. }
  26. export default function useRoute() {
  27. return routeState
  28. }