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

如何在v-for中访问被子元素变量遮蔽的同名props?

解决props属性与v-for遍历属性重名的访问问题

当v-for遍历的子元素属性和props属性重名时,模板中props的对应属性会被遍历变量遮蔽,可通过以下几种方式解决:

方法1:解构遍历项时重命名冲突属性

直接在v-for的解构语法里给冲突属性起别名,避免遮蔽props的属性:

<template>
    <ul>
        <li v-for="{ id, name: itemName } in data" :key="id">
           {{ itemName }} and {{ name }} <!-- name 指向 props 的 name -->
        </li>
    </ul>
</template>
<script setup lang="ts">
const props = defineProps({ data: Array, name: String });
</script>

方法2:在脚本中给props属性起别名

如果不想修改遍历的解构逻辑,可在<script setup>里给props的冲突属性重命名,模板里用别名访问:

<template>
    <ul>
        <li v-for="{ id, name } in data" :key="id">
           {{ name }} and {{ parentName }} <!-- parentName 指向 props 的 name -->
        </li>
    </ul>
</template>
<script setup lang="ts">
const props = defineProps({ data: Array, name: String });
const { name: parentName } = props; // 给props的name起别名
</script>

方法3:不使用解构,直接访问遍历项的属性

放弃解构遍历项,直接通过遍历项对象访问其属性,避免和props属性冲突:

<template>
    <ul>
        <li v-for="item in data" :key="item.id">
           {{ item.name }} and {{ name }} <!-- name 指向 props 的 name -->
        </li>
    </ul>
</template>
<script setup lang="ts">
const props = defineProps({ data: Array, name: String });
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:15:48