Vue3 如何獲取url中的參數(shù)? 有哪幾種方法? 請(qǐng)舉例說明
1. vue3 如何獲取url中的參數(shù)
在Vue3中獲取URL參數(shù)的方法主要分為基于vue-router和原生JavaScript兩種方式,具體取決于是否使用路由庫。以下是詳細(xì)說明及示例:
1.1.基于vue-router 4.x(推薦,適用于單頁應(yīng)用)
Vue3通常配合vue-router 4.x使用,此時(shí)URL參數(shù)(動(dòng)態(tài)路由參數(shù)、查詢參數(shù))可通過路由實(shí)例獲取。
1.1.1. 組合式API中使用 useRoute(推薦)
在<script setup>或組合式API中,通過useRoute鉤子獲取當(dāng)前路由對(duì)象,其中:
? route.params:獲取動(dòng)態(tài)路由參數(shù)(URL路徑中的參數(shù),如/user/:id中的id)。
? route.query:獲取查詢參數(shù)(URL中?后的參數(shù),如/user?name=test中的name)。
示例:假設(shè)路由配置如下(router/index.js):
import { createRouter, createWebHistory } from'vue-router'
importUserfrom'../views/User.vue'
const routes = [
// 動(dòng)態(tài)路由參數(shù)(:userId為參數(shù)名)
{ path: '/user/:userId', component: User },
// 支持查詢參數(shù)(無需在路由中定義)
{ path: '/profile', component: () =>import('../views/Profile.vue') }
]
const router = createRouter({
history: createWebHistory(),
routes
})
exportdefault router在User.vue中獲取動(dòng)態(tài)參數(shù):
<template>
<div>用戶ID:{{ userId }}</div>
</template>
<script setup>
import { useRoute } from 'vue-router'
// 獲取當(dāng)前路由對(duì)象
const route = useRoute()
// 動(dòng)態(tài)路由參數(shù)(URL為/user/100時(shí),userId為'100')
const userId = route.params.userId
console.log('動(dòng)態(tài)參數(shù):', userId) // 輸出:'100'(字符串類型)
</script>在Profile.vue中獲取查詢參數(shù):
<template>
<div>用戶名:{{ userName }},年齡:{{ age }}</div>
</template>
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
// 查詢參數(shù)(URL為/profile?name=張三&age=20時(shí))
const userName = route.query.name // '張三'
const age = route.query.age // '20'(注意:默認(rèn)是字符串類型,需手動(dòng)轉(zhuǎn)數(shù)字)
console.log('查詢參數(shù):', { userName, age })
</script>1.1.2. 選項(xiàng)式API中使用 this.$route
如果使用選項(xiàng)式API(非<script setup>),可通過this.$route直接獲取路由參數(shù),用法與Vue2類似。
示例:
<template>
<div>用戶ID:{{ $route.params.userId }}</div>
</template>
<script>
export default {
mounted() {
// 動(dòng)態(tài)參數(shù)
console.log('動(dòng)態(tài)參數(shù):', this.$route.params.userId)
// 查詢參數(shù)(如URL為/user/100?tab=info時(shí))
console.log('查詢參數(shù):', this.$route.query.tab) // 'info'
}
}
</script>1.1.3. 路由守衛(wèi)中獲取參數(shù)
在路由守衛(wèi)(如beforeEach)中,可通過to參數(shù)(目標(biāo)路由對(duì)象)獲取參數(shù)。
示例:
// router/index.js
router.beforeEach((to, from, next) => {
// 動(dòng)態(tài)參數(shù)(如跳轉(zhuǎn)至/user/100時(shí))
console.log('目標(biāo)路由動(dòng)態(tài)參數(shù):', to.params.userId) // '100'
// 查詢參數(shù)(如跳轉(zhuǎn)至/profile?name=張三時(shí))
console.log('目標(biāo)路由查詢參數(shù):', to.query.name) // '張三'
next()
})1.2. 原生JavaScript方法(不依賴vue-router,適用于簡單場景)
如果未使用vue-router,可通過window.location解析URL參數(shù)(僅支持查詢參數(shù),不支持動(dòng)態(tài)路由參數(shù))。
1.2.1. 實(shí)現(xiàn)思路:
1. 通過window.location.search獲取URL中?后的查詢字符串(如?name=test&age=20)。
2. 解析字符串為鍵值對(duì)對(duì)象。
示例:
<template>
<div>解析結(jié)果:{{ params }}</div>
</template>
<script setup>
// 解析URL查詢參數(shù)的工具函數(shù)
const getUrlParams = () => {
const params = {}
const searchStr = window.location.search.slice(1) // 去掉開頭的`?`,得到`name=test&age=20`
if (searchStr) {
searchStr.split('&').forEach(item => {
const [key, value] = item.split('=')
// 解碼特殊字符(如空格、中文)
params[key] = decodeURIComponent(value)
})
}
return params
}
// 調(diào)用函數(shù)獲取參數(shù)(假設(shè)URL為http://example.com?name=張三&age=20)
const params = getUrlParams()
console.log(params) // { name: '張三', age: '20' }
</script>1.3. 總結(jié)
方法 | 適用場景 | 特點(diǎn) |
(組合式) | 使用vue-router的單頁應(yīng)用 | 簡潔,支持動(dòng)態(tài)參數(shù)和查詢參數(shù) |
(選項(xiàng)式) | 使用vue-router的選項(xiàng)式API組件 | 兼容舊寫法,用法與Vue2一致 |
路由守衛(wèi) | 路由跳轉(zhuǎn)前需要獲取參數(shù)的場景 | 全局?jǐn)r截時(shí)使用 |
原生JavaScript解析 | 不使用vue-router的簡單頁面 | 僅支持查詢參數(shù),需手動(dòng)處理解碼 |
實(shí)際開發(fā)中,推薦使用vue-router的useRoute方法,更符合Vue3的組合式API風(fēng)格且支持完整的路由參數(shù)類型。


















