Nuxt/packages/app/src/plugins/router/index.ts

54 lines
1.1 KiB
TypeScript
Raw Normal View History

import { shallowRef } from 'vue'
import {
createRouter,
createWebHistory,
createMemoryHistory,
RouterLink
} from 'vue-router'
import NuxtPage from './NuxtPage.vue'
2021-03-29 09:40:51 +00:00
import type { Plugin } from '@nuxt/app'
2021-04-09 13:48:39 +00:00
// @ts-ignore
import routes from '#build/routes'
// @ts-ignore
export default <Plugin> function router (nuxt) {
const { app } = nuxt
app.component('NuxtPage', NuxtPage)
app.component('NuxtLink', RouterLink)
const routerHistory = process.client
? createWebHistory()
: createMemoryHistory()
const router = createRouter({
history: routerHistory,
routes
})
app.use(router)
nuxt.provide('router', router)
const previousRoute = shallowRef(router.currentRoute.value)
router.afterEach((_to, from) => {
previousRoute.value = from
})
Object.defineProperty(app.config.globalProperties, 'previousRoute', {
get: () => previousRoute.value
})
nuxt.hook('app:created', async () => {
if (process.server) {
router.push(nuxt.ssrContext.url)
}
try {
await router.isReady()
if (!router.currentRoute.value.matched.length) {
// TODO
}
} catch (err) {
// TODO
}
})
}