|
1 |
| -import Vue, { getCurrentInstance, reactive } from 'vue'; |
| 1 | +import Vue, { effectScope, getCurrentInstance, reactive } from 'vue'; |
2 | 2 | import VueRouter, { NavigationGuard, Route, RouterOptions } from 'vue-router';
|
3 | 3 | import { OUT_OF_SCOPE, warn } from './utils';
|
4 | 4 |
|
5 |
| -export { |
| 5 | +export type { |
6 | 6 | RouteMeta,
|
7 | 7 | RouterOptions,
|
8 | 8 | RouteRecord,
|
@@ -49,22 +49,34 @@ export function useRouter(): Router {
|
49 | 49 | return undefined as any;
|
50 | 50 | }
|
51 | 51 |
|
52 |
| -let currentRoute: RouteLocationNormalizedLoaded; |
| 52 | +let currentRoute: Route; |
53 | 53 |
|
54 |
| -export function useRoute() { |
55 |
| - const router = useRouter(); |
| 54 | +export function useRoute(): RouteLocationNormalizedLoaded { |
| 55 | + const inst = getCurrentInstance(); |
| 56 | + if (!inst) { |
| 57 | + warn(OUT_OF_SCOPE); |
| 58 | + return undefined as any; |
| 59 | + } |
56 | 60 | if (!currentRoute) {
|
57 |
| - const inst = getCurrentInstance(); |
58 |
| - if (!inst) { |
59 |
| - warn(OUT_OF_SCOPE); |
60 |
| - return; |
61 |
| - } |
62 |
| - currentRoute = reactive({ ...inst.proxy.$route } as Route); |
63 |
| - router.afterEach((to) => Object.assign(currentRoute, to)); |
| 61 | + const scope = effectScope(true); |
| 62 | + scope.run(() => { |
| 63 | + const { $router } = inst.proxy; |
| 64 | + currentRoute = reactive(assign({}, $router.currentRoute)) as any; |
| 65 | + $router.afterEach((to) => { |
| 66 | + assign(currentRoute, to); |
| 67 | + }); |
| 68 | + }); |
64 | 69 | }
|
65 | 70 | return currentRoute;
|
66 | 71 | }
|
67 | 72 |
|
| 73 | +function assign(target: Record<string, any>, source: Record<string, any>) { |
| 74 | + for (const key of Object.keys(source)) { |
| 75 | + target[key] = source[key]; |
| 76 | + } |
| 77 | + return target; |
| 78 | +} |
| 79 | + |
68 | 80 | export function onBeforeRouteLeave(leaveGuard: NavigationGuard) {
|
69 | 81 | const inst = getCurrentInstance();
|
70 | 82 | if (!inst) {
|
|
0 commit comments