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

Vue列表循环传递key值至子组件后无法渲染的问题咨询

问题分析与解决方案

你遇到的问题核心在于:key是Vue的特殊保留属性,它专门用于列表渲染的Diff算法优化,并不会被当作普通的prop传递给子组件,所以子组件里试图通过props: ["key"]来接收值是拿不到的。

解决步骤

我们只需要把id作为一个独立的prop传递给子组件即可,具体修改如下:

1. 修改父组件的绑定

在父组件的v-for循环里,新增一个对id的绑定(注意不用key作为prop名):

<single-news-template 
  v-for="m in data" 
  v-bind:key="m.id" 
  v-bind:id="m.id"  <!-- 新增这一行,传递id作为单独的prop -->
  v-bind:title="m.title" 
  v-bind:text="m.text" 
  v-bind:date="m.date"
></single-news-template>

2. 修改子组件的接收与渲染

把子组件里的keyprop替换成id,同时模板里也对应改成{{id}}:

<template>
  <v-list-item dense >
    <v-list-item-avatar>
      <v-avatar color="indigo" size="36">
        <span class="white--text headline">{{id}}</span> <!-- 这里改成id -->
      </v-avatar>
    </v-list-item-avatar>
    <v-list-item-content>
      <v-list-item-title><a href="">{{title}}</a></v-list-item-title>
      <v-list-item-subtitle>[...]{{text}}[...] </v-list-item-subtitle>
      <v-list-item-subtitle>{{date}}</v-list-item-subtitle>
    </v-list-item-content>
  </v-list-item>
</template>

<script>
export default {
  name: "SingleNewsTemplate",
  props: ["id","title", "text", "date"]  // 这里把key换成id
}
</script>

补充说明

  • key的唯一作用是帮助Vue识别列表中每个元素的唯一性,从而更高效地更新DOM,它不能被用于组件的数据传递。
  • 如果担心id和其他属性重名,也可以给这个prop起个更明确的名字,比如itemId,只需要保持父组件绑定和子组件接收的名称一致即可(父组件用:item-id="m.id",子组件props里写"itemId")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:27:47