feat(nuxt): add wrapped useRoute and useRouter composables (#2406)

This commit is contained in:
Daniel Roe 2021-12-17 09:15:03 +00:00 committed by GitHub
parent df33474730
commit 6c1cb11b95
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 34 additions and 10 deletions

View File

@ -6,8 +6,7 @@ const UnsupportedImports = new Set(['useAsyncData', 'useFetch'])
const CapiHelpers = new Set(Object.keys(CompositionApi))
const ImportRewrites = {
vue: '@vue/composition-api',
'vue-router': '#app'
vue: '@vue/composition-api'
}
export async function setupAutoImports () {
@ -28,6 +27,10 @@ export async function setupAutoImports () {
}
}
// Add auto-imports that are added by ad-hoc modules in nuxt 3
autoImports.push({ name: 'useRouter', as: 'useRouter', from: '#app' })
autoImports.push({ name: 'useRoute', as: 'useRoute', from: '#app' })
// Add bridge-only auto-imports
autoImports.push({ name: 'useNuxt2Meta', as: 'useNuxt2Meta', from: '#app' })
})

View File

@ -24,14 +24,6 @@ export const Nuxt3AutoImports: AutoImportSource[] = [
'useMeta'
]
},
// vue-router
{
from: 'vue-router',
names: [
'useRoute',
'useRouter'
]
},
// vue-demi (mocked)
{
from: 'vue-demi',

View File

@ -35,6 +35,12 @@ export default defineNuxtModule({
}
})
nuxt.hook('autoImports:extend', (autoImports) => {
const composablesFile = resolve(runtimeDir, 'composables')
autoImports.push({ name: 'useRouter', as: 'useRouter', from: composablesFile })
autoImports.push({ name: 'useRoute', as: 'useRoute', from: composablesFile })
})
// Add router plugin
addPlugin(resolve(runtimeDir, 'router'))

View File

@ -0,0 +1,23 @@
import { computed, reactive } from 'vue'
import type { Router, RouteLocationNormalizedLoaded } from 'vue-router'
import { useNuxtApp } from '#app'
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
}