router.mjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Utilities
  2. import { computed, nextTick, onScopeDispose, resolveDynamicComponent, toRef } from 'vue';
  3. import { getCurrentInstance, hasEvent, IN_BROWSER, propsFactory } from "../util/index.mjs"; // Types
  4. export function useRoute() {
  5. const vm = getCurrentInstance('useRoute');
  6. return computed(() => vm?.proxy?.$route);
  7. }
  8. export function useRouter() {
  9. return getCurrentInstance('useRouter')?.proxy?.$router;
  10. }
  11. export function useLink(props, attrs) {
  12. const RouterLink = resolveDynamicComponent('RouterLink');
  13. const isLink = computed(() => !!(props.href || props.to));
  14. const isClickable = computed(() => {
  15. return isLink?.value || hasEvent(attrs, 'click') || hasEvent(props, 'click');
  16. });
  17. if (typeof RouterLink === 'string') {
  18. return {
  19. isLink,
  20. isClickable,
  21. href: toRef(props, 'href')
  22. };
  23. }
  24. const link = props.to ? RouterLink.useLink(props) : undefined;
  25. return {
  26. isLink,
  27. isClickable,
  28. route: link?.route,
  29. navigate: link?.navigate,
  30. isActive: link && computed(() => props.exact ? link.isExactActive?.value : link.isActive?.value),
  31. href: computed(() => props.to ? link?.route.value.href : props.href)
  32. };
  33. }
  34. export const makeRouterProps = propsFactory({
  35. href: String,
  36. replace: Boolean,
  37. to: [String, Object],
  38. exact: Boolean
  39. }, 'router');
  40. let inTransition = false;
  41. export function useBackButton(router, cb) {
  42. let popped = false;
  43. let removeBefore;
  44. let removeAfter;
  45. if (IN_BROWSER) {
  46. nextTick(() => {
  47. window.addEventListener('popstate', onPopstate);
  48. removeBefore = router?.beforeEach((to, from, next) => {
  49. if (!inTransition) {
  50. setTimeout(() => popped ? cb(next) : next());
  51. } else {
  52. popped ? cb(next) : next();
  53. }
  54. inTransition = true;
  55. });
  56. removeAfter = router?.afterEach(() => {
  57. inTransition = false;
  58. });
  59. });
  60. onScopeDispose(() => {
  61. window.removeEventListener('popstate', onPopstate);
  62. removeBefore?.();
  63. removeAfter?.();
  64. });
  65. }
  66. function onPopstate(e) {
  67. if (e.state?.replaced) return;
  68. popped = true;
  69. setTimeout(() => popped = false);
  70. }
  71. }
  72. //# sourceMappingURL=router.mjs.map