navigateTo
navigateTo 是一個輔助函式,可透過程式碼導覽使用者。
navigateTo
在客戶端和伺服器端都可用(但在 Nitro 路由中不可用)。用法
navigateTo
在伺服器端和客戶端都可用。它可以在 Nuxt 上下文內使用,或者直接使用,以執行頁面導覽。
若要從伺服器端點傳送重新導向,請改用
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
中的 external
參數會影響如何處理導覽至網址的方式
- 沒有
external: true
的情況:- 內部網址會如預期般導覽。
- 外部網址會擲回錯誤。
- 有
external: true
的情況:- 內部網址會以完整頁面重新載入的方式導覽。
- 外部網址會如預期般導覽。
範例
<script setup lang="ts">
// will throw an error;
// navigating to an external URL is not allowed by default
await navigateTo('https://nuxt.dev.org.tw')
// will redirect successfully with the 'external' parameter set to 'true'
await navigateTo('https://nuxt.dev.org.tw', {
external: true
})
</script>
使用 open()
<script setup lang="ts">
// will open 'https://nuxt.dev.org.tw' in a new tab
await navigateTo('https://nuxt.dev.org.tw', {
open: {
target: '_blank',
windowFeatures: {
width: 500,
height: 500
}
}
})
</script>
類型
navigateTo(to: RouteLocationRaw | undefined | null, options?: NavigateToOptions) => Promise<void | NavigationFailure> | RouteLocationRaw
interface NavigateToOptions {
replace?: boolean
redirectCode?: number
external?: boolean
open?: OpenOptions
}
呼叫
navigateTo
時,請務必使用 await
或 return
來處理其結果。參數
to
類型:RouteLocationRaw
| undefined
| null
預設值:'/'
to
可以是要重新導向到的純文字字串或路由物件。當作為 undefined
或 null
傳遞時,它會預設為 '/'
。
範例
// 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
時,允許導覽至外部網址。否則,navigateTo
將會擲回錯誤,因為預設不允許外部導覽。open
(選用)
類型:OpenOptions
允許使用視窗的 open() 方法導覽至網址。此選項僅適用於客戶端,且在伺服器端將會被忽略。
接受下列屬性的物件target
類型:string
預設值:'_blank'
一個不含空格的字串,指定要將資源載入其中的瀏覽環境名稱。windowFeatures
(選用)
類型:OpenWindowFeatures
接受下列屬性的物件popup
(選用)
類型:boolean
width
或innerWidth
(選用)
類型:number
height
或innerHeight
(選用)
類型:number
left
或screenX
(選用)
類型:number
top
或screenY
(選用)
類型:number
noopener
(選用)
類型:boolean
noreferrer
(選用)
類型:boolean
請參閱 文件,以取得關於 windowFeatures 屬性的更詳細資訊。