VUE3中使用router傳遞參數

最基礎使用router的方式就是來傳遞不同的頁面,不過router同時也具有傳遞參數的功能,這篇文章整理了如何怎麼傳遞參數以及設置方式。

目錄

基礎設置

在使用vue router時,最基礎的設置方法如下

 

在更進階一點,在 Vue Router 中,可以通過多種方式在路由之間傳遞變數,例如 路徑參數、查詢參數 或 狀態對象。以下是詳細介紹和實現方式:

路徑參數 (params)


在路由中設置帶參數的路徑:

import User from './User.vue'

const routes = [
  {
    path: '/users/:id', // :id 是路由參數
    name: 'User',
    component: User,
  },
];

 

在這種設置底下,我們建立的路由會是像這樣子的路徑

/users/johnny 或是 /users/jolyne

模板則是以route.params的形式暴露

User {{ $route.params.id }}

我們也可以在同個路由中設置多個參數,例如

/users/:username

/users/:username/posts/:postId


查詢參數 (query)



使用query不需要特別設置路由。

導航的時候直接使用 query 傳遞變數:

router.push({ path: '/user', query: { id: 123 } });


生成的 URL 為:/user?id=123

模板則是以route.query的形式接收參數

router.push

使用router.push的方式會在history留下紀錄,因此如果點擊上一頁時會回到前個網址

router-link也是相同的方法

用router.push傳遞參數的方式有很多種

// 純字串
router.push('/users/johnny')

// 路徑
router.push({ path: '/users/johnny' })

// 命名+參數
router.push({ name: 'user', params: { username: 'johnny' } })

// query參數 (/register?plan=private)
router.push({ path: '/register', query: { plan: 'private' } })

// hash (/about#team)
router.push({ path: '/about', hash: '#team' })

透過props傳遞參數

 

使用props的形式,我們就不需要依賴route,在使用上可以更加靈活

<!-- 在User.vue中定義props -->
<script setup>
defineProps({
  id: String
})
</script>

<template>
  <div>
    User {{ id }}
  </div>
</template>

此時template的id就不需要靠route.param傳遞,而是內部的id

同時id會作為參數傳遞給route

路由的設置

const routes = [
  { path: '/user/:id', component: User, props: true }
]

使用狀態對象 (state)

當不想在 URL 中顯示參數時,可以使用狀態對象:

router.push({ path: '/user', state: { id: 123 } });


在目標組件中,使用 router.currentRoute.value.state 獲取參數:


 

https://router.vuejs.org/zh/guide/essentials/dynamic-matching.html