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

如何在Vue的v-for循环中通过方法修改子项数据?

Vue方法中更新子元素年龄的解决方案

你已经正确把child对象传入了coolstuff方法,直接在方法内修改它的age属性即可完成需求:

coolstuff (child) {
  // 直接修改child的age属性
  child.age = 20;
}

为什么这样可行?

因为child是从people数组中传递过来的对象引用,修改对象的属性会直接同步到原数据中,Vue的响应式系统会自动捕捉到这个变化并更新视图,和你用内联代码v-on:input="child.age = 20"的效果完全一致。

完整代码示例

模板代码

<template>
    <div v-for="(person, personIndex) in people" :key="personIndex">
        <div v-for="(child, childIndex) in person.children" :key="childIndex">
            <input type="checkbox" v-on:input="coolstuff(child)">
            <!-- 可添加此内容实时查看年龄变化 -->
            {{ child.name }} - 年龄:{{ child.age }}
        </div>
    </div>
</template>

脚本代码

export default defineComponent({
    data: () => ({
        people: [
            {
                name: "john",
                age: 50,
                children:[
                    { 
                        name: "sally",
                        age: 4
                    },
                    { 
                        name: "joe",
                        age: 5
                    }
                ]
            }           
        ]
    }),
    methods: {
        coolstuff (child) {
            child.age = 20;
        }
    }   
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:15:38