|
1 | 1 | import Vue from 'vue'
|
2 |
| -import { getCurrentInstance } from '@vue/composition-api' |
| 2 | +import { computed, ComputedRef, getCurrentInstance, reactive, shallowRef } from '@vue/composition-api' |
3 | 3 | import VueRouter, { NavigationGuard, Route, RouterOptions, RouteConfig } from 'vue-router'
|
4 | 4 | import { OUT_OF_SCOPE, warn } from './utils'
|
5 | 5 |
|
@@ -34,36 +34,41 @@ export function createRouter(options: RouterOptions) {
|
34 | 34 | }
|
35 | 35 |
|
36 | 36 |
|
37 |
| -export function useRouter() { |
| 37 | +export function useRouter(): Router { |
38 | 38 | const inst = getCurrentInstance()
|
39 | 39 | if (inst) {
|
40 | 40 | return inst.proxy.$router as Router
|
41 | 41 | }
|
42 | 42 | warn(OUT_OF_SCOPE)
|
43 |
| - return undefined as unknown as Router |
| 43 | + return undefined as any |
44 | 44 | }
|
45 | 45 |
|
| 46 | + |
46 | 47 | export interface RouteLocationNormalized extends Route {}
|
47 | 48 | export interface RouteLocationNormalizedLoaded extends Route {}
|
48 | 49 |
|
49 |
| -const ROUTE_KEYS = [ |
| 50 | + |
| 51 | +const currentRoute = shallowRef(VueRouter.START_LOCATION); |
| 52 | +const computedRoute = {} as { |
| 53 | + [key in keyof Route]: ComputedRef<Route[key]> |
| 54 | +} |
| 55 | +for (const key of [ |
50 | 56 | 'name', 'meta', 'path', 'hash', 'query',
|
51 | 57 | 'params', 'fullPath', 'matched', 'redirectedFrom'
|
52 |
| -] as const |
| 58 | +] as const) { |
| 59 | + computedRoute[key] = computed<any>(() => currentRoute.value[key]); |
| 60 | +} |
| 61 | +let reactiveRoute: Route |
53 | 62 |
|
54 |
| -export function useRoute() { |
| 63 | +export function useRoute(): RouteLocationNormalizedLoaded { |
55 | 64 | const router = useRouter()
|
56 |
| - if (router) { |
57 |
| - const route = {} as RouteLocationNormalizedLoaded |
58 |
| - for (const key of ROUTE_KEYS) { |
59 |
| - Object.defineProperty(route, key, { |
60 |
| - enumerable: true, |
61 |
| - get: () => router.currentRoute[key], |
62 |
| - }) |
63 |
| - } |
64 |
| - return route |
| 65 | + if (!router) return undefined as any |
| 66 | + if (!reactiveRoute) { |
| 67 | + currentRoute.value = router.currentRoute |
| 68 | + router.afterEach(to => currentRoute.value = to); |
| 69 | + reactiveRoute = reactive(computedRoute) |
65 | 70 | }
|
66 |
| - return undefined as unknown as RouteLocationNormalizedLoaded |
| 71 | + return reactiveRoute |
67 | 72 | }
|
68 | 73 |
|
69 | 74 |
|
|
0 commit comments