navigateTo

navigateTo 是一个辅助函数,用于以编程方式导航用户。

用法

¥Usage

navigateTo 可在服务器端和客户端使用。它可以在 Nuxt 上下文 中使用,也可以直接用于页面导航。

¥navigateTo is available on both server side and client side. It can be used within the Nuxt context, or directly, to perform page navigation.

确保在调用 navigateTo 时始终在其结果上使用 awaitreturn。¥Make sure to always use await or return on result of navigateTo when calling it.
navigateTo 不能在 Nitro 路由中使用。要在 Nitro 路由中执行服务器端重定向,请改用 sendRedirect

在 Vue 组件中

¥Within a Vue Component

<script setup lang="ts">
// passing 'to' as a string
await navigateTo('/search')

// ... or as a route object
await navigateTo({ path: '/search' })

// ... or as a route object with query parameters
await navigateTo({
  path: '/search',
  query: {
    page: 1,
    sort: 'asc'
  }
})
</script>

在路由中间件中

¥Within Route Middleware

export default defineNuxtRouteMiddleware((to, from) => {
  if (to.path !== '/search') {
    // setting the redirect code to '301 Moved Permanently'
    return navigateTo('/search', { redirectCode: 301 })
  }
})

在路由中间件中使用 navigateTo 时,必须返回其结果以确保中间件执行流程正常运行。

¥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
  }
})

在这种情况下,navigateTo 将被执行但不会返回,这可能会导致意外行为。

¥In this case, navigateTo will be executed but not returned, which may lead to unexpected behavior.

Read more in Docs > Guide > Directory Structure > Middleware.

导航到外部 URL

¥Navigating to an External URL

navigateTo 中的 external 参数会影响 URL 导航的处理方式:

¥The external parameter in navigateTo influences how navigating to URLs is handled:

  • 不包含 external: true
    • 内部 URL 导航正常。
    • 外部 URL 会引发错误。
  • 包含 external: true
    • 内部 URL 导航时会重新加载整个页面。
    • 外部 URL 可按预期导航。

示例

¥Example

<script setup lang="ts">
// will throw an error;
// navigating to an external URL is not allowed by default
await navigateTo('https://nuxt.nodejs.cn')

// will redirect successfully with the 'external' parameter set to 'true'
await navigateTo('https://nuxt.nodejs.cn', {
  external: true
})
</script>

在新标签页中打开页面

¥Opening a Page in a New Tab

<script setup lang="ts">
// will open 'https://nuxt.nodejs.cn' in a new tab
await navigateTo('https://nuxt.nodejs.cn', {
  open: {
    target: '_blank',
    windowFeatures: {
      width: 500,
      height: 500
    }
  }
})
</script>

类型

¥Type

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 }>

参数

¥Parameters

to

类型:RouteLocationRaw | undefined | null

¥Type: RouteLocationRaw | undefined | null

默认:'/'

¥Default: '/'

to 可以是纯字符串,也可以是要重定向到的路由对象。当传递 undefinednull 时,它将默认为 '/'

¥to can be a plain string or a route object to redirect to. When passed as undefined or null, it will default to '/'.

示例

¥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(可选)

¥options (optional)

类型:NavigateToOptions

¥Type: NavigateToOptions

接受以下属性的对象:

¥An object accepting the following properties:

  • replace
    • 类型:boolean
    • 默认:false
    • 默认情况下,navigateTo 将指定的路由推送到客户端的 Vue Router 实例中。
      可以通过将 replace 设置为 true 来更改此行为,以指示应替换给定的路由。
  • redirectCode
    • 类型:number
    • 默认:302
    • navigateTo 重定向到给定路径,并在服务器端进行重定向时默认将重定向代码设置为 302 Found
      你可以通过提供不同的 redirectCode 来修改此默认行为。通常,301 Moved Permanently 可用于永久重定向。
  • external
    • 类型:boolean
    • 默认:false
    • 设置为 true 时允许导航到外部 URL。否则,navigateTo 将抛出错误,因为默认情况下不允许外部导航。
  • open
    • 类型:OpenOptions
    • 允许使用窗口的 open() 方法导航到 URL。此选项仅适用于客户端,在服务器端将被忽略。
      接受以下属性的对象:
    • target
      • 类型:string
      • 默认:'_blank'
      • 不带空格的字符串,用于指定加载资源的浏览上下文的名称。
    • windowFeatures
      • 类型:OpenWindowFeatures
      • 接受以下属性的对象:
        属性类型描述
        popupboolean请求最小化弹出窗口而不是新标签页,UI 功能由浏览器决定。
        widthinnerWidthnumber指定内容区域的宽度(最小 100 像素),包括滚动条。
        heightinnerHeightnumber指定内容区域的高度(最小 100 像素),包括滚动条。
        leftscreenXnumber设置新窗口相对于屏幕左边缘的水平位置。
        topscreenYnumber设置新窗口相对于屏幕顶部边缘的垂直位置。
        noopenerboolean阻止新窗口通过 window.opener 访问原始窗口。
        noreferrerboolean阻止发送 Referer 标头并隐式启用 noopener

        有关 windowFeatures 属性的更多详细信息,请参阅 documentation