Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

feat(nuxt): allow getRouteFromPath to use objects #5900

Merged
merged 3 commits into from
Aug 22, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions packages/nuxt/src/app/plugins/router.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { reactive, h } from 'vue'
import { parseURL, parseQuery, withoutBase, isEqual, joinURL } from 'ufo'
import { parseURL, stringifyParsedURL, parseQuery, stringifyQuery, withoutBase, isEqual, joinURL } from 'ufo'
import { createError } from 'h3'
import { defineNuxtPlugin, clearError, navigateTo, showError, useRuntimeConfig } from '..'
import { callWithNuxt } from '../nuxt'
Expand Down Expand Up @@ -28,9 +28,13 @@ interface Route {
meta: Record<string, any>;
}

function getRouteFromPath (fullPath: string | Record<string, unknown>) {
function getRouteFromPath (fullPath: string | Partial<Route>) {
if (typeof fullPath === 'object') {
throw new TypeError('[nuxt] Route location object cannot be resolved when vue-router is disabled (no pages).')
fullPath = stringifyParsedURL({
pathname: fullPath.path || '',
search: stringifyQuery(fullPath.query || {}),
hash: fullPath.hash || ''
})
}

const url = parseURL(fullPath.toString())
Expand Down Expand Up @@ -79,7 +83,7 @@ interface Router {
afterEach: (guard: RouterHooks['navigate:after']) => () => void
onError: (handler: RouterHooks['error']) => () => void
// Routes
resolve: (url: string | Record<string, unknown>) => Route
resolve: (url: string | Partial<Route>) => Route
addRoute: (parentName: string, route: Route) => void
getRoutes: () => any[]
hasRoute: (name: string) => boolean
Expand Down Expand Up @@ -107,7 +111,7 @@ export default defineNuxtPlugin<{ route: Route, router: Router }>((nuxtApp) => {
const baseURL = useRuntimeConfig().app.baseURL

const route: Route = reactive(getRouteFromPath(initialURL))
async function handleNavigation (url: string, replace?: boolean): Promise<void> {
async function handleNavigation (url: string | Partial<Route>, replace?: boolean): Promise<void> {
try {
// Resolve route
const to = getRouteFromPath(url)
Expand All @@ -127,7 +131,7 @@ export default defineNuxtPlugin<{ route: Route, router: Router }>((nuxtApp) => {
// Perform navigation
Object.assign(route, to)
if (process.client) {
window.history[replace ? 'replaceState' : 'pushState']({}, '', joinURL(baseURL, url))
window.history[replace ? 'replaceState' : 'pushState']({}, '', joinURL(baseURL, to.fullPath))
if (!nuxtApp.isHydrating) {
// Clear any existing errors
await callWithNuxt(nuxtApp, clearError)
Expand Down