如何在导航时传递查询参数(query)和路径参数(params)?

解读

国内面试官问这个问题,通常不是单纯让你背 API,而是想确认三件事:

  1. 你是否清楚“params 必须配动态路由、query 不用”这一根本差异;
  2. 你是否能在 Options API、Composition API、setup-script 三种写法下都写对;
  3. 你是否知道 Vue3 + Vite 时代“路由传参”与“组件取值”的最佳实践(类型安全、响应式、刷新不丢值)。
    答不到这三层,很容易被追问“刷新页面 params 丢了怎么办”“query 如何声明类型”“路由守卫里怎么取参”。

知识点

  1. 路由表声明
    • 路径参数必须先在 path 里占坑:/user/:id
    • 查询参数无需声明,直接 ?key=value
  2. 声明式导航
    • <router-link> 的 to 属性可接受字符串、对象、命名路由三种写法
  3. 编程式导航
    • Vue2:this.$router.push({ name: 'User', params: { id: 1 }, query: { tab: 'profile' } })
    • Vue3:import { useRouter } from 'vue-router'; const router = useRouter(); router.push({ ... })
  4. 组件内取参
    • Options API:this.$route.params.id / this.$route.query.tab
    • Composition API:import { useRoute } from 'vue-router'; const route = useRoute(); route.params.id / route.query.tab
  5. 响应式与刷新
    • params 依赖路由记录,F5 刷新后若路由表无对应动态段会 404;query 不受限
    • 国内项目常把“详情 id”同时放进 params 和 query,刷新时优先读 query 做降级
  6. 类型安全(TS)
    • 在 src/router/index.ts 给路由记录加泛型:RouteRecordRaw & { meta?: { title: string } }
    • 组件里用 route.params.id as string 或自己写 ParamsInterface
  7. 路由守卫
    • 全局 beforeEach 里可直接 to.params / to.query 做权限拦截,如电商后台“tab=price”需要财务角色

答案

下面给出“Vue3 + <script setup> + TS”的完整写法,覆盖“导航”与“取值”两端,可直接用在面试手写环节。

  1. 路由表
// src/router/index.ts
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/product/:id',          // 路径参数 id
    name: 'Product',
    component: () => import('@/views/Product.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router
  1. 列表页——编程式导航(带 params + query)
<script setup lang="ts">
import { useRouter } from 'vue-router'

const router = useRouter()

function goDetail(row: { productId: number }) {
  router.push({
    name: 'Product',              // 必须用 name 才能带 params
    params: { id: row.productId }, // 路径参数
    query: { source: 'list', t: Date.now() } // 查询参数
  })
}
</script>
  1. 详情页——取参 + 类型断言
<script setup lang="ts">
import { useRoute } from 'vue-router'
import { computed, watchEffect } from 'vue'

const route = useRoute()

// 路径参数
const productId = computed(() => route.params.id as string)

// 查询参数
const source = computed(() => (route.query.source as string) || 'direct')

// 监听变化,处理后端换 id 场景
watchEffect(() => {
  console.log('当前商品', productId.value, '来源', source.value)
  fetchDetail(productId.value)
})
</script>
  1. 模板里直接使用
<template>
  <h1>商品 {{ productId }}</h1>
  <p>来源:{{ source }}</p>
</template>
  1. 刷新不丢值兜底(可选)
// 在详情页 onMounted 里
if (!route.params.id && route.query.id) {
  router.replace({ name: 'Product', params: { id: route.query.id } })
}

拓展思考

  1. 同一参数“既想 SEO 友好又想刷新不丢”,国内主流做法是把关键 id 放在路径,附加 flag 放 query,例如 /product/10086?ref=wechat。
  2. 若用 Nuxt3,可直接使用 useRoute().params 与 useRouter().push(),但注意服务端渲染阶段 params 已固化,不能再做客户端跳转拼接。
  3. 微前端场景(qiankun、wujie)下,子应用路由带 query 会被主应用透传,params 可能丢失,建议统一用 query 做跨应用通信。
  4. 大型中台项目会给每个路由写 meta.paramsKeys 数组,在全局 beforeEach 做“参数缺失自动补全”或“非法字符 403”,这是面试官爱问的“你在工程化层面怎么保证参数安全”。