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

Vue组件传值报错:解构Props丢失响应性,数组无法传递给子组件

Vue Props传递丢失响应式及列表不显示问题修复

核心问题分析

  1. Props解构丢失响应式:子组件中直接解构defineProps返回值,破坏了Vue的响应式绑定逻辑,导致出现报错"Destructuring the props will cause the value to lose reactivity"。
  2. 未循环渲染列表:子组件模板只有固定的一行空数据,没有遍历传递过来的候选人数组,因此数据无法正常展示。

具体修复步骤

1. 修复Props响应式问题

defineProps返回的是一个响应式代理对象,直接解构会把响应式值转换为普通值,失去对父组件数据变化的追踪能力。有两种可靠修复方式:

  • 方式一:直接使用props对象(推荐,代码简洁直观)
  • 方式二:用toRefs解构(适合多props场景,保留响应式特性)

2. 实现列表循环渲染

在子组件的<tbody>标签内,使用v-for遍历候选人数组,同时绑定唯一:key值,确保Vue的Diff算法能正确更新DOM。

修改后的完整代码

子组件(TabellaCandidati.vue)

<template>
    <table class="table">
        <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">Name</th>
                <th scope="col">Surname</th>
            </tr>
        </thead>
        <tbody>
            <!-- 循环渲染候选人数据 -->
            <tr v-for="candidato in candidati" :key="candidato.id">
                <th scope="row">{{ candidato.id }}</th>
                <td>{{ candidato.nome }}</td>
                <td>{{ candidato.cognome }}</td>
            </tr>
            <!-- 空数据状态提示 -->
            <tr v-if="candidati.length === 0">
                <td colspan="3" class="text-center">暂无候选人数据</td>
            </tr>
        </tbody>
    </table>
</template>

<script setup>
import { defineProps } from 'vue';

// 方式一:直接使用响应式props对象,同时添加类型校验增强代码健壮性
const props = defineProps({
    candidati: {
        type: Array,
        required: true,
        default: () => []
    }
});

// 若想简化变量名,可使用toRefs解构(需引入toRefs):
// import { defineProps, toRefs } from 'vue';
// const { candidati } = toRefs(defineProps(['candidati']));
</script>

父组件模板调整(可选,遵循Vue命名规范)

将props绑定名改为小驼峰(Vue官方推荐props使用小驼峰命名):

<TabellaCandidati :candidati="Candidati"></TabellaCandidati>

额外建议

父组件中的Candidati变量名也建议改为小驼峰candidati,保持整个项目的代码风格统一,避免大小写混乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 10:42:56