Использование
Функция navigateTo доступна как на сервере, так и на клиенте. Ее можно использовать внутри Nuxt-контекста или напрямую для осуществления постраничной навигации.
await or return on result of navigateTo when calling it.navigateTo cannot be used within Nitro routes. To perform a server-side redirect in Nitro routes, use sendRedirect instead.Внутри компонента Vue
<script setup lang="ts">
// передаем 'to' в виде строки
await navigateTo('/search')
// ... или в виде объекта маршрута
await navigateTo({ path: '/search' })
// ... или как объект маршрута с параметрами запроса
await navigateTo({
path: '/search',
query: {
page: 1,
sort: 'asc'
}
})
</script>
Внутри Route Middleware
export default defineNuxtRouteMiddleware((to, from) => {
if (to.path !== '/search') {
// установка кода редиректа на '301 Moved Permanently'
return navigateTo('/search', { redirectCode: 301 })
}
})
When using navigateTo within route middleware, you must return its result to ensure the middleware execution flow works correctly.
For example, the following implementation will not work as expected:
export default defineNuxtRouteMiddleware((to, from) => {
if (to.path !== '/search') {
// ❌ This will not work as expected
navigateTo('/search', { redirectCode: 301 })
return
}
})
In this case, navigateTo will be executed but not returned, which may lead to unexpected behavior.
Navigating to an External URL
Параметр external в navigateTo влияет на то, как будет осуществляться переход по URL:
- Без параметра
external: true:- Внутренние URL переходят, как и ожидалось.
- Внешние URL-адреса выдают ошибку.
- С
external: true:- Внутренние URL переходят с полной перезагрузкой страницы.
- Внешние URL переходят, как и ожидалось.
Пример
<script setup lang="ts">
// выкинет ошибку;
// переход на внешний URL по умолчанию запрещен
await navigateTo('https://nuxt.com')
// произойдет успешная переадресация с параметром 'external', установленным в значение 'true'
await navigateTo('https://nuxt.com', {
external: true
})
</script>
Opening a Page in a New Tab
<script setup lang="ts">
// откроет 'https://nuxt.com' в новой вкладке
await navigateTo('https://nuxt.com', {
open: {
target: '_blank',
windowFeatures: {
width: 500,
height: 500
}
}
})
</script>
Тип
function navigateTo(
to: RouteLocationRaw | undefined | null,
options?: NavigateToOptions
) => Promise<void | NavigationFailure | false> | false | void | RouteLocationRaw
interface NavigateToOptions {
replace?: boolean
redirectCode?: number
external?: boolean
open?: OpenOptions
}
type OpenOptions = {
target: string
windowFeatures?: OpenWindowFeatures
}
type OpenWindowFeatures = {
popup?: boolean
noopener?: boolean
noreferrer?: boolean
} & XOR<{ width?: number }, { innerWidth?: number }>
& XOR<{ height?: number }, { innerHeight?: number }>
& XOR<{ left?: number }, { screenX?: number }>
& XOR<{ top?: number }, { screenY?: number }>
Параметры
to
Тип: RouteLocationRaw | undefined | null
По умолчанию: '/'
to может быть простой строкой или объектом маршрута, на который нужно перенаправить. Если передать undefined или null, то по умолчанию будет указано '/'.
Example
// Passing the URL directly will redirect to the '/blog' page
await navigateTo('/blog')
// Using the route object, will redirect to the route with the name 'blog'
await navigateTo({ name: 'blog' })
// Redirects to the 'product' route while passing a parameter (id = 1) using the route object.
await navigateTo({ name: 'product', params: { id: 1 } })
options (опционально)
Тип: NavigateToOptions
Объект, принимающий следующие свойства:
replace- Тип:
boolean - По умолчанию:
false - По умолчанию
navigateToпробрасывает заданный маршрут в экземпляр Vue Router на стороне клиента.
Это поведение можно изменить, установивreplaceвtrue, чтобы указать, что данный маршрут должен быть заменен.
- Тип:
redirectCode- Тип:
number - По умолчанию:
302 navigateToперенаправляет на указанный путь и устанавливает код перенаправления на302 Foundпо умолчанию, когда перенаправление происходит на стороне сервера.
Это поведение по умолчанию можно изменить, указав другойredirectCode. Обычно для постоянных перенаправлений используется301 Moved Permanently.- Тип:
external- Тип:
boolean - По умолчанию:
false - Позволяет переходить на внешний URL, если установлено значение
true. В противном случаеnavigateToвыдаст ошибку, так как внешняя навигация по умолчанию запрещена.
- Тип:
open- Тип:
OpenOptions - Позволяет перейти к URL с помощью метода open() окна. Этот параметр применим только на стороне клиента и будет игнорироваться на стороне сервера.
Объект, принимающий следующие свойства:target- Тип:
string - По умолчанию:
'_blank' - A string, without whitespace, specifying the name of the browsing context the resource is being loaded into.
- Тип:
windowFeatures- Тип:
OpenWindowFeatures - An object accepting the following properties:
Property Type Description popupbooleanRequests a minimal popup window instead of a new tab, with UI features decided by the browser. widthorinnerWidthnumberSpecifies the content area's width (minimum 100 pixels), including scrollbars. heightorinnerHeightnumberSpecifies the content area's height (minimum 100 pixels), including scrollbars. leftorscreenXnumberSets the horizontal position of the new window relative to the left edge of the screen. toporscreenYnumberSets the vertical position of the new window relative to the top edge of the screen. noopenerbooleanPrevents the new window from accessing the originating window via window.opener.noreferrerbooleanPrevents the Referer header from being sent and implicitly enables noopener.
Refer to the documentation for more detailed information on the windowFeatures properties.
- Тип:
- Тип: