You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中如何通过router-link向路由组件传递props参数?

Vue Router 原生支持路由传参及 props 接收,针对你的产品详情跳转场景,有三种成熟可落地的实现方式,可根据项目实际情况选择:


方案1:路由开启props模式,通过params传递全量数据(和你现有写法适配度最高)

  • 修改路由配置,为ProductDetail路由开启props: true配置,路由匹配到的params参数会自动作为props注入目标组件,记得保留路径上的id占位,避免刷新页面参数丢失:
// 路由配置文件(通常为router/index.js)
const routes = [
  // 其余已有路由配置保持不变
  {
    path: '/product/:id',
    name: 'ProductDetail',
    component: () => import('@/views/ProductDetail.vue'),
    props: true // 核心配置:开启params转props
  }
]
  • 修改父组件中router-link的跳转参数,把需要传递的产品全量字段都写入params中:
<div class="product-card" v-for="Product in Products" :key="Product.id">
  <router-link :to="{
    name: 'ProductDetail',
    params: {
      id: Product.id,
      name: Product.name,
      Detail: Product.Detail
      // 其余需要传递的产品字段可直接在此追加
    }
  }">
    <h5>{{Product.name}}</h5>
  </router-link>
</div>
  • 在ProductDetail组件中声明props接收参数即可直接使用:
<script>
export default {
  props: {
    id: [Number, String],
    name: String,
    Detail: String
  },
  mounted() {
    // 直接通过this访问props拿到数据,无需额外处理$route
    console.log('当前产品详情:', this.id, this.name, this.Detail)
  }
}
</script>

*注意:如果路由路径没有配置对应的参数占位,刷新页面后,除了路径匹配到的id字段外,其余params参数会丢失。


方案2:query传参(无需修改路由配置)

如果不想调整现有路由配置,可以直接把产品数据放在query中传递,参数会自动拼接在URL后缀:

<router-link :to="{
  name: 'ProductDetail',
  query: Product // 可直接传入整个产品对象
}">
  <h5>{{Product.name}}</h5>
</router-link>

目标组件中通过this.$route.query即可拿到全部产品数据,缺点是参数会明文展示在URL上,数据量较大时URL会过长,仅适合传递少量简单字段。


方案3:id传参+本地/全局状态匹配(生产环境推荐,稳定性最高)

如果产品数据字段多、不希望参数暴露在URL上,可以采用更稳妥的实现逻辑:

  • 路由跳转时依然只传递产品id,和你现有写法完全一致
  • 将全量产品列表存入Pinia/Vuex全局状态,或者跳转前存入sessionStorage
  • 进入ProductDetail组件后,用拿到的id从全局状态/缓存中匹配对应id的完整产品数据

这种方式完全不存在参数丢失、URL过长的问题,刷新页面也能正常拿到数据,适合正式业务场景使用。


内容的提问来源于stack exchange,提问作者Muhammad Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 22:18:14