如何在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
相关产品推荐
相关产品推荐

