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

Vue中如何将v-for的index拼接至:key的item.path后生成指定格式?

解决Vue中v-for的key拼接需求

这事儿超容易搞定!Vue的模板语法支持直接在属性绑定里写表达式,你只需要把item.path和循环的index做字符串拼接就行,给你两种常用的写法:

方法1:ES6模板字符串(推荐,可读性更高)

用反引号包裹的模板字符串,通过${}插入变量,直接生成你要的/abc-1这种格式:

<template v-for="(item, index) in menuList">
  <MenuItem 
    v-if="item.children.length <= 1" 
    class='child' 
    :name="item.children[0].name" 
    :key="`${item.path}-${index}`"
  >
    <!-- 你的MenuItem内部内容 -->
  </MenuItem>
</template>

方法2:传统字符串拼接

如果项目暂时不支持ES6语法,也可以用加号直接拼接字符串:

<template v-for="(item, index) in menuList">
  <MenuItem 
    v-if="item.children.length <= 1" 
    class='child' 
    :name="item.children[0].name" 
    :key="item.path + '-' + index"
  >
    <!-- 你的MenuItem内部内容 -->
  </MenuItem>
</template>

小提醒

  • 数字类型的index会自动被转换成字符串,不用额外处理类型问题
  • 用path + index的组合能确保每个循环项的key唯一,避免Vue渲染时弹出重复key的警告

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:14:20