navigateTo

原始檔
navigateTo 是一個幫助函式,用於程式化地導航使用者。

使用

navigateTo 在伺服器端和客戶端都可用。它可以在 Nuxt 上下文中使用,也可以直接用於執行頁面導航。

在呼叫 navigateTo 時,請務必始終使用 awaitreturn 處理其結果。
navigateTo 不能在 Nitro 路由中使用。要在 Nitro 路由中執行伺服器端重定向,請使用sendRedirect代替。

在 Vue 元件中

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

在路由中介軟體中

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

在路由中介軟體中使用 navigateTo 時,你必須返回其結果,以確保中介軟體執行流程正常工作。

例如,以下實現將無法按預期工作

export default defineNuxtRouteMiddleware((to, from) => {
  if (to.path !== '/search') {
    // ❌ This will not work as expected
    navigateTo('/search', { redirectCode: 301 })
    return
  }
})

在這種情況下,navigateTo 將被執行但不會返回,這可能導致意外行為。

更多資訊請閱讀:文件 > 4 X > 指南 > 目錄結構 > App > Middleware

navigateTo 中的 external 引數會影響如何處理導航到 URL

  • 不帶 external: true:
    • 內部 URL 按預期導航。
    • 外部 URL 會丟擲錯誤。
  • external: true:
    • 內部 URL 會進行全頁面重新載入。
    • 外部 URL 按預期導航。

示例

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

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

在新標籤頁中開啟頁面

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

型別

簽名
export 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 }>

引數

@BobbieGoede

型別: RouteLocationRaw| undefined | null

預設: '/'

to 可以是一個純字串或一個路由物件,用於重定向。當傳入 undefinednull 時,它將預設為 '/'

示例

// 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
    • 設定為 true 時允許導航到外部 URL。否則,navigateTo 將丟擲錯誤,因為預設情況下不允許外部導航。
  • open
    • 型別: OpenOptions
    • 允許使用 window 的open()方法導航到 URL。此選項僅適用於客戶端,在伺服器端將被忽略。
      一個接受以下屬性的物件
    • target
      • 型別: string
      • 預設: '_blank'
      • 一個不帶空格的字串,指定資源載入到的瀏覽上下文的名稱。
    • windowFeatures
      • 型別: OpenWindowFeatures
      • 一個接受以下屬性的物件
        屬性型別描述
        popupboolean請求一個最小的彈出視窗而不是新標籤頁,UI 功能由瀏覽器決定。
        widthinnerWidthnumber指定內容區域的寬度(最小 100 畫素),包括捲軸。
        heightinnerHeightnumber指定內容區域的高度(最小 100 畫素),包括捲軸。
        leftscreenXnumber設定新視窗相對於螢幕左邊緣的水平位置。
        topscreenYnumber設定新視窗相對於螢幕上邊緣的垂直位置。
        noopenerboolean阻止新視窗透過 window.opener 訪問源視窗。
        noreferrerboolean阻止傳送 Referer 頭部並隱式啟用 noopener

        請參考文件獲取有關 windowFeatures 屬性的更詳細資訊。