mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-26 15:42:09 +00:00
feat(nuxt): add wrapped useRoute
and useRouter
composables (#2406)
This commit is contained in:
parent
df33474730
commit
6c1cb11b95
@ -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' })
|
||||
})
|
||||
|
@ -24,14 +24,6 @@ export const Nuxt3AutoImports: AutoImportSource[] = [
|
||||
'useMeta'
|
||||
]
|
||||
},
|
||||
// vue-router
|
||||
{
|
||||
from: 'vue-router',
|
||||
names: [
|
||||
'useRoute',
|
||||
'useRouter'
|
||||
]
|
||||
},
|
||||
// vue-demi (mocked)
|
||||
{
|
||||
from: 'vue-demi',
|
||||
|
@ -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'))
|
||||
|
||||
|
23
packages/nuxt3/src/pages/runtime/composables.ts
Normal file
23
packages/nuxt3/src/pages/runtime/composables.ts
Normal 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
|
||||
}
|
Loading…
Reference in New Issue
Block a user