AdSense

網頁

2026/1/5

Vue Nuxt 3 程式式導航 Programmatic Navigation

本篇介紹如何在Vue Nuxt 3中使用程式式導航(Programmatic Navigation),白話一點就是「使用程式來進行路由頁面跳轉」。


在Nuxt 3中路由連結經常都是用<NuxtLink>元件來跳轉到不同頁面,但也可以使用Vue Routerrouter.push()來跳轉頁面,例如:

const router = useRouter()
router.push(`/user`)


事前要求

參考「Vue Nuxt 3 動態路由 Dynamic Route」,本篇依此修改。


調整pages/home/export/[orderId].vue

原本的出口業務的訂單明細頁中的返回是使用<NuxtLink to="/home/export">返回列表</NuxtLink>,下面改為使用按鈕來觸發程式跳轉。

pages/home/export/[orderId].vue

<script setup>
const router = useRouter()
const route = useRoute()
const orderId = route.params.orderId

function back() {
  router.push(`/home/export`)
}
</script>

<template>
  <div>
    <h1>訂單詳情 #{{ orderId }}</h1>
    <!-- <NuxtLink to="/home/export">返回列表</NuxtLink> -->

    <button @click="back">返回</button>
  </div>
</template>

github


點擊按鈕即可觸發router.push(`/home/export`)返回[出口業務]頁面。



若輸入的路由不存在,可使用Catch-all Route捕捉

沒有留言:

AdSense