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

Vue中如何在router-link的to属性中使用组件props传递的id值

Vue中如何在router-link的to属性中使用组件props传递的id值

嘿,我之前也踩过这个坑!你现在的问题核心是没搞清楚Vue模板里文本插值和属性绑定的区别,直接在to属性里用{{id}}是行不通的,Vue会把它当成普通字符串处理,不会替换成你props里的真实id值。

给你两种简单的解决办法,看你需求选就行:

方法一:用模板字符串直接拼接路径(适合简单场景)

把to属性改成绑定语法(加个冒号:),然后用ES6模板字符串拼接你的路径和id:

<template>
  <div class="item">
    <!-- 这里用:to绑定,模板字符串拼接id -->
    <router-link :to="`/entry/${id}`">
      <slot name="name"></slot>
    </router-link>
  </div>
</template>

<script setup>
import { defineProps } from 'vue'
defineProps({
  id: {
    type: Number,
    required: true
  }
})
</script>

这里的:to是v-bind:to的缩写,告诉Vue这个属性值是一个JS表达式,这样就能正确读取到props传递过来的id,拼出正确的路径啦。

方法二:用命名路由+参数对象(更推荐,易维护)

如果你的路由配置里给这个页面设置了命名路由,那用这种方式会更灵活,以后改路由路径也不用改组件里的代码。

比如你的路由配置是这样的:

// 路由配置文件(比如router/index.js)
const routes = [
  {
    path: '/entry/:id',
    name: 'EntryDetail', // 给路由起个名字
    component: () => import('../views/EntryDetail.vue')
  }
]

那组件里可以这么写:

<template>
  <div class="item">
    <router-link 
      :to="{ 
        name: 'EntryDetail', 
        params: { id: id } 
      }"
    >
      <slot name="name"></slot>
    </router-link>
  </div>
</template>

这种方式是通过路由的name来跳转,params里的id会自动对应到路由path里的:id参数,后续如果要把/entry/:id改成/item/:id,只要路由name不变,组件里的代码完全不用改,维护起来省心很多。

你的

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 11:24:34