文章目录
- 一、使用 `params` 传递参数
- 1. 基本路由格式
- 2. 可选参数的使用
- 代码示例
 
 
- 二、使用 `query` 传递参数
- 1. 基本路由格式
- 代码示例
 
 
- 总结
一、使用 params 传递参数
 
1. 基本路由格式
在Vue中,使用params传递参数是通过路由的动态片段来完成的。在路由配置中,使用:定义一个参数占位符,然后在路由跳转时将实际值传递给参数。
const routes = [{path: '/user/:id', // 定义参数占位符 ':id'component: UserProfile}
]
定义一个路由 /user/:id,其中 :id 是参数占位符。在路由跳转时传递实际的用户ID值:
// 在代码中进行路由跳转并传递参数
this.$router.push({ path: `/user/${userId}` })
2. 可选参数的使用
通过在路由定义中使用问号(?)来实现。
const routes = [{path: '/user/:id?', // 定义可选参数 ':id?'component: UserProfile}
]
/user和/user/:id都可以匹配这个路由。当参数是可选时,如果不提供参数,Vue会将其视为undefined。
代码示例
<template><div><h1>User Profile</h1><p v-if="$route.params.id">User ID: {{ $route.params.id }}</p><p v-else>User ID is not provided</p></div>
</template><script>
export default {mounted() {// 获取传递过来的用户IDconst userId = this.$route.params.idif (userId) {// 根据用户ID加载用户数据this.loadUserProfile(userId)} else {// 处理没有提供用户ID的情况console.log('User ID is not provided')}},methods: {loadUserProfile(userId) {// 发起API请求或执行其他操作,加载用户数据console.log(`Loading data for user ID: ${userId}`)}}
}
</script>
二、使用 query 传递参数
 
1. 基本路由格式
与params不同,query参数是以键值对的形式附加到URL的查询字符串中的。在路由配置中,不需要定义参数占位符,而是直接在路由跳转时传递参数。
const routes = [{path: '/user',component: UserProfile}
]
将参数直接作为查询参数传递:
// 在代码中进行路由跳转并传递参数
this.$router.push({ path: '/user', query: { id: userId } })
代码示例
<template><div><h1>User Profile</h1><p>User ID: {{ $route.query.id }}</p></div>
</template><script>
export default {mounted() {// 获取传递过来的用户IDconst userId = this.$route.query.idif (userId) {// 根据用户ID加载用户数据this.loadUserProfile(userId)} else {// 处理没有提供用户ID的情况console.log('User ID is not provided')}},methods: {loadUserProfile(userId) {// 发起API请求或执行其他操作,加载用户数据console.log(`Loading data for user ID: ${userId}`)}}
}
</script>
总结
- 使用 params时,参数直接包含在路由的路径中,适用于对参数的格式和可见性有要求的情况。通过在路径中使用问号(?),还可以使某些参数变为可选。
- 使用 query时,参数作为查询字符串传递,适用于需要将参数保留在URL中的情况,或者需要传递多个参数的情况。