Skip to content

Commit e109aee

Browse files
committed
fix(vue-router): create a detached scope
for `useRoute` (#4, #5)
1 parent cb92c43 commit e109aee

File tree

1 file changed

+24
-12
lines changed

1 file changed

+24
-12
lines changed

src/vue-router.ts

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import Vue, { getCurrentInstance, reactive } from 'vue';
1+
import Vue, { effectScope, getCurrentInstance, reactive } from 'vue';
22
import VueRouter, { NavigationGuard, Route, RouterOptions } from 'vue-router';
33
import { OUT_OF_SCOPE, warn } from './utils';
44

5-
export {
5+
export type {
66
RouteMeta,
77
RouterOptions,
88
RouteRecord,
@@ -49,22 +49,34 @@ export function useRouter(): Router {
4949
return undefined as any;
5050
}
5151

52-
let currentRoute: RouteLocationNormalizedLoaded;
52+
let currentRoute: Route;
5353

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+
}
5660
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+
});
6469
}
6570
return currentRoute;
6671
}
6772

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+
6880
export function onBeforeRouteLeave(leaveGuard: NavigationGuard) {
6981
const inst = getCurrentInstance();
7082
if (!inst) {

0 commit comments

Comments
 (0)