fix(nuxt3): define route in plugin rather than composable (#2443)

This commit is contained in:
Daniel Roe 2021-12-20 10:37:00 +00:00 committed by GitHub
parent d98fe1207e
commit f668d7457f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 16 deletions

View File

@ -1,4 +1,3 @@
import { computed, reactive } from 'vue'
import type { Router, RouteLocationNormalizedLoaded } from 'vue-router'
import { useNuxtApp } from '#app'
@ -6,18 +5,6 @@ export const useRouter = () => {
return useNuxtApp().$router as Router
}
export const useRoute = (): RouteLocationNormalizedLoaded => {
const nuxtApp = useNuxtApp()
if (nuxtApp._route) {
return nuxtApp._route
}
const currentRoute = (nuxtApp.$router as Router).currentRoute
// https://github.com/vuejs/vue-router-next/blob/master/src/router.ts#L1192-L1200
nuxtApp._route = reactive(Object.fromEntries(
Object.keys(currentRoute.value).map(key => [key, computed(() => currentRoute.value[key])])
) as any)
return nuxtApp._route
export const useRoute = () => {
return useNuxtApp()._route as RouteLocationNormalizedLoaded
}

View File

@ -1,4 +1,4 @@
import { shallowRef } from 'vue'
import { computed, reactive, shallowRef } from 'vue'
import {
createRouter,
createWebHistory,
@ -46,6 +46,14 @@ export default defineNuxtPlugin((nuxtApp) => {
get: () => previousRoute.value
})
// https://github.com/vuejs/vue-router-next/blob/master/src/router.ts#L1192-L1200
const route = {}
for (const key in router.currentRoute.value) {
route[key] = computed(() => router.currentRoute.value[key])
}
nuxtApp._route = reactive(route)
nuxtApp.hook('app:created', async () => {
if (process.server) {
router.push(nuxtApp.ssrContext.url)