Vue3 路由配置與跳轉傳參完整指南

目錄

一、路由配置

1. 基本路由配置

2. 動態路由配置

3. 可選參數配置

二、路由跳轉與傳參

1. 聲明式導航 (模板中)

2. 編程式導航 (JavaScript中)

三、參數接收

1. 接收動態路由參數

2. 接收查詢參數

3. 監聽參數變化

四、高級用法

1. 路由元信息

2. 路由守衛控制

3. 動態添加路由

五、完整示例

路由配置示例

組件使用示例


一、路由配置

1. 基本路由配置

// router/index.js
import { createRouter, createWebHistory } from 'vue-router'const routes = [{path: '/',name: 'Home',component: () => import('@/views/Home.vue')},{path: '/about',name: 'About',component: () => import('@/views/About.vue')}
]const router = createRouter({history: createWebHistory(),routes
})export default router

2. 動態路由配置

const routes = [// 動態段以冒號開始{path: '/user/:id',name: 'User',component: () => import('@/views/User.vue')},// 多個動態參數{path: '/post/:postId/comment/:commentId',name: 'PostComment',component: () => import('@/views/PostComment.vue')}
]

3. 可選參數配置

{path: '/user/:id?',  // 問號表示可選name: 'UserOptional',component: () => import('@/views/UserOptional.vue')
}

二、路由跳轉與傳參

1. 聲明式導航 (模板中)

<!-- 基本跳轉 -->
<router-link to="/about">關于我們</router-link><!-- 動態路由傳參 -->
<router-link :to="'/user/' + userId">用戶主頁</router-link>
<router-link :to="{ name: 'User', params: { id: userId } }">用戶主頁</router-link><!-- 查詢參數傳參 -->
<router-link :to="{ path: '/search', query: { keyword: 'vue' } }">搜索</router-link>

2. 編程式導航 (JavaScript中)

import { useRouter } from 'vue-router'const router = useRouter()// 1. 動態路由傳參
router.push('/user/123')  // 路徑方式
router.push({ name: 'User', params: { id: 123 } })  // 命名路由方式// 2. 查詢參數傳參
router.push({path: '/search',query: {keyword: 'vue',page: 1}
})// 3. 替換當前路由 (不保留歷史記錄)
router.replace({ path: '/login' })// 4. 前進/后退
router.go(1)  // 前進
router.go(-1) // 后退

三、參數接收

1. 接收動態路由參數

import { useRoute } from 'vue-router'const route = useRoute()// 接收單個參數
const userId = route.params.id// 接收多個參數
const postId = route.params.postId
const commentId = route.params.commentId// 可選參數處理
const optionalId = route.params.id || 'default'

2. 接收查詢參數

import { useRoute } from 'vue-router'const route = useRoute()// 獲取查詢參數
const keyword = route.query.keyword
const page = Number(route.query.page) || 1  // 帶類型轉換和默認值// 處理數組參數 (如 ?tags=vue&tags=js)
const tags = Array.isArray(route.query.tags) ? route.query.tags : [route.query.tags].filter(Boolean)

3. 監聽參數變化

import { watch } from 'vue'
import { useRoute } from 'vue-router'const route = useRoute()// 監聽動態參數變化
watch(() => route.params.id,(newId) => {console.log('用戶ID變化:', newId)fetchUserData(newId)}
)// 監聽查詢參數變化
watch(() => route.query,(newQuery) => {console.log('查詢參數變化:', newQuery)},{ deep: true }
)

四、高級用法

1. 路由元信息

// 路由配置
{path: '/admin',name: 'Admin',component: () => import('@/views/Admin.vue'),meta: {requiresAuth: true,role: 'admin'}
}// 組件中獲取
const route = useRoute()
const requiresAuth = route.meta.requiresAuth

2. 路由守衛控制

router.beforeEach((to, from, next) => {if (to.meta.requiresAuth && !isAuthenticated()) {next({path: '/login',query: { redirect: to.fullPath }})} else {next()}
})

3. 動態添加路由

// 添加單個路由
router.addRoute({path: '/new-route',name: 'NewRoute',component: () => import('@/views/NewRoute.vue')
})// 添加嵌套路由
router.addRoute('Admin', {path: 'settings',name: 'AdminSettings',component: () => import('@/views/AdminSettings.vue')
})

五、完整示例

路由配置示例

// router/index.js
import { createRouter, createWebHistory } from 'vue-router'const routes = [{path: '/',name: 'Home',component: () => import('@/views/Home.vue')},{path: '/product/:id',name: 'Product',component: () => import('@/views/Product.vue'),props: true // 將params作為props傳遞},{path: '/search',name: 'Search',component: () => import('@/views/Search.vue')},{path: '/login',name: 'Login',component: () => import('@/views/Login.vue'),meta: {guestOnly: true}}
]const router = createRouter({history: createWebHistory(),routes
})// 全局路由守衛
router.beforeEach((to, from, next) => {const isAuth = localStorage.getItem('token')if (to.meta.guestOnly && isAuth) {next({ name: 'Home' }) // 已登錄用戶不能訪問登錄頁} else {next()}
})export default router

組件使用示例

<script setup>
import { useRouter, useRoute } from 'vue-router'
import { onMounted, watch } from 'vue'const router = useRouter()
const route = useRoute()// 編程式導航
const navigateToProduct = (id) => {router.push({name: 'Product',params: { id },query: { from: 'home' }})
}// 接收參數
const productId = route.params.id
const searchQuery = route.query.q// 監聽參數變化
watch(() => route.params.id,(newId) => {console.log('產品ID變化:', newId)fetchProduct(newId)}
)// 接收props形式的參數 (需要路由配置 props: true)
const props = defineProps({id: String
})
</script><template><div><!-- 聲明式導航 --><router-link :to="{ name: 'Product', params: { id: 123 }, query: { from: 'home' } }">產品123</router-link><!-- 編程式導航按鈕 --><button @click="navigateToProduct(456)">查看產品456</button><!-- 顯示當前路由參數 --><p>當前產品ID: {{ productId }}</p><p v-if="route.query.q">搜索詞: {{ searchQuery }}</p></div>
</template>

總結

  1. 路由配置:使用?createRouter?創建路由,createWebHistory?創建歷史模式

  2. 動態路由:使用?:param?語法定義動態段

  3. 跳轉方式

    • 聲明式:<router-link>

    • 編程式:router.push()/router.replace()

  4. 傳參方式

    • 動態參數:params

    • 查詢參數:query

  5. 參數接收:使用?useRoute()?獲取當前路由信息

  6. 高級功能:路由守衛、元信息、動態路由添加等

按照這些方法,可以靈活地在 Vue3 項目中實現各種路由需求。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/904807.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/904807.shtml
英文地址,請注明出處:http://en.pswp.cn/news/904807.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Vibe Coding: 優點與缺點

如果你最近在開發圈子里,你很可能聽說過這個新趨勢"vibe coding"(氛圍編程)。 我只能說我對此感受復雜。以下是原因。 優勢 在構建新項目時,靠著氛圍編程達到成功感覺很自由!但對于遺留代碼來說情況就不同了,盡管也不是不可能。 實時反饋和快速迭代 Cursor(…

7:點云處理—眼在手外標定

1.制作模板 dev_update_off ()dev_set_color (green)dev_close_window ()WindowHeight:740WindowWidth :740dev_open_window(0, 0, 540, 540, black, WindowHandle)Instruction : [Rotate: Left button,Zoom: Shift left button,Move: Ctrl left button]read_object_mod…

AI賦能智能客服革新:R2AIN SUITE 如何破解醫療行業服務難題?

一、什么是智能客服&#xff1f; 智能客服是基于人工智能技術&#xff08;AI&#xff09;的客戶服務解決方案&#xff0c;通過自然語言處理&#xff08;NLP&#xff09;、機器學習、大模型等核心技術&#xff0c;實現多模態交互、自動化應答、知識庫管理、流程優化等功能。其核…

(undone) MIT6.S081 Lec17 VM for APP 學習筆記

url: https://mit-public-courses-cn-translatio.gitbook.io/mit6-s081/lec17-virtual-memory-for-applications-frans/17.1-ying-yong-cheng-xu-shi-yong-xu-ni-nei-cun-suo-xu-yao-de-te-xing 17.1 應用程序使用虛擬內存所需要的特性 今天的話題是用戶應用程序使用的虛擬內存…

使用 OpenSSL 吊銷 Kubernetes(k8s)的 kubeconfig 里的用戶證書

一.用 OpenSSL 依據已有的自簽名 CA 注銷簽發的證書的步驟 1. 準備工作 你得有自簽名 CA 的私鑰&#xff08;通常是 .key 文件&#xff09;、CA 證書&#xff08;通常是 .crt 文件&#xff09;以及證書吊銷列表&#xff08;CRL&#xff09;文件。若還沒有 CRL 文件&#xff0c…

循環卷積(Circular Convolutions)

最近看論文發現了一個叫循環卷積的東西&#xff0c;這里學習并記錄一下&#xff0c;方便以后查閱。 循環卷積&#xff08;Circular Convolutions&#xff09; 循環卷積&#xff08;Circular Convolutions&#xff09;1. 什么是循環卷積2. 數學定義關鍵點 3. 循環卷積與線性卷積…

【計算機視覺】Car-Plate-Detection-OpenCV-TesseractOCR:車牌檢測與識別

Car-Plate-Detection-OpenCV-TesseractOCR&#xff1a;車牌檢測與識別技術深度解析 在計算機視覺領域&#xff0c;車牌檢測與識別&#xff08;License Plate Detection and Recognition, LPDR&#xff09;是一個極具實用價值的研究方向&#xff0c;廣泛應用于智能交通系統、安…

MATLAB制作柱狀圖與條圖:數據可視化的基礎利器

一、什么是柱狀圖與條圖&#xff1f; 柱狀圖和條圖都是用來表示分類數據的常見圖表形式&#xff0c;它們的核心目的是通過矩形的長度來比較各類別的數值大小。條圖其實就是“橫著的柱狀圖”&#xff0c;它們的本質是一樣的&#xff1a;用矩形的長度表示數值大小&#xff0c;不同…

[計算機科學#13]:算法

【核知坊】&#xff1a;釋放青春想象&#xff0c;碼動全新視野。 我們希望使用精簡的信息傳達知識的骨架&#xff0c;啟發創造者開啟創造之路&#xff01;&#xff01;&#xff01; 內容摘要&#xff1a; 算法是解決問題的系統化步驟&#xff0c;不同的問題…

HTTP傳輸大文件的方法、連接管理以及重定向

目錄 1. HTTP傳輸大文件的方法 1.1. 數據壓縮 1.2. 分塊傳輸 1.3. 范圍請求 1.4. 多段數據 2. HTTP的連接管理 2.1. 短連接 2.2. 長連接 2.3. 隊頭阻塞 3. HTTP的重定向和跳轉 3.1. 重定向的過程 3.2. 重定向狀態碼 3.3. 重定向的應用場景 3.4. 重定向的相關問題…

PostgreSQL 18 Beta 1發布,有哪些功能亮點?

PostgreSQL 全球開發組于 2025 年 5 月 8 日發布了第一個 PostgreSQL 18 Beta 版本&#xff0c;現已開放下載。雖然細節可能會有所改變&#xff0c;但是該版本包含了 PostgreSQL 18 最終正式版中所有新功能的預覽。 以下是 PostgreSQL 18 引入的部分關鍵功能亮點。 性能優化 …

vue dev-tools插件

背景 在項目上用到vue技術&#xff0c;在bilibili上學習vue&#xff0c;期間老師推薦使用vue dev-tools調試神器&#xff0c;所以過來安轉和使用了&#xff0c;用了感覺不錯&#xff0c;希望給大家帶來效率的提升。 定義 Vue DevTools 是一款旨在增強 Vue 開發者體驗的工具&am…

單片機-FLASH軟件模擬EEPROM,提升flash保存重要參數的使用壽命

目錄 1. FLASH和EEPROM讀寫數據的對比 ??2. FLASH模擬EEPROM的原理 ??3. FLASH模擬EEPROM的優點 ??4. 實戰項目工程代碼 1. FLASH和EEPROM讀寫數據的對比 1.1 擦除操作 EEPROM通常支持按單字節擦除和寫入&#xff0c;這一特性使其非常適合需要頻繁更新小量數據的應…

探索Stream流:高效數據處理的秘密武器

不可變集合 stream流 Stream流的使用步驟&#xff1a; 先得到一條Stream流&#xff08;流水線&#xff09;&#xff0c;并把數據放上去 使用中間方法對流水線上的數據進行操作 使用終結方法對流水線上的數據進行操作 Stream流的中間方法 注意1&#xff1a;中間方法&#xff0…

vue3筆記(自存)

1. Vue3簡介 2020年9月18日&#xff0c;Vue.js發布版3.0版本&#xff0c;代號&#xff1a;One Piece&#xff08;n 經歷了&#xff1a;4800次提交、40個RFC、600次PR、300貢獻者 官方發版地址&#xff1a;Release v3.0.0 One Piece vuejs/core 截止2023年10月&#xff0c;最…

實驗4 mySQL查詢和視圖

一、實驗目的 掌握SELECT語句的基本語法多表連接查詢GROUP BY的使用方法。ORDER BY的使用方法。 二、實驗步驟、內容、結果 實驗內容&#xff1a; 實驗4.1數據庫的查詢 目的與要求 (1)掌握SELECT語句的基本語法。 (2)掌握子查詢的表示。 (3)掌握連接查詢的表示。 (4)掌…

【bug】fused_bias_act_kernel.cu卡住沒反應

簡述 在推理人臉修復face restoration算法 GPEN的時候&#xff0c;發現有時候fused_bias_act_kernel.cu卡住沒反應。 解決 清理下緩存&#xff0c;讓程序自己再編譯下

.net/C#進程間通信技術方案總結

C# 應用進程間通信(IPC)技術方案 進程間通信(Inter-Process Communication, IPC)是不同進程之間交換數據和消息的機制。以下是C#中常用的IPC技術方案&#xff1a; 1. 命名管道(Named Pipes) 適用于本地機器上的進程通信&#xff0c;支持雙向通信。 ??服務端示例??&…

阿里云服務器數據庫故障排查指南?

阿里云服務器數據庫故障排查指南? 以下是針對阿里云服務器&#xff08;如ECS自建數據庫或阿里云RDS等托管數據庫&#xff09;的故障排查指南&#xff0c;涵蓋常見問題的定位與解決方案&#xff1a; 一、數據庫連接失敗 檢查網絡連通性 ECS自建數據庫 確認安全組規則放行數據庫…

深度學習 ———— 遷移學習

遷移學習原理 什么是遷移學習&#xff1f; 遷移學習利用在大規模數據集&#xff08;如ImageNet&#xff09;上預訓練的模型&#xff0c;改裝小數據集&#xff08;如CIFAR-10&#xff09;。優勢&#xff1a; 減少訓練時間&#xff1a;預訓練模型已學習通用特征&#xff08;如邊…