vue里 import { ref ,reactive} from 'vue'; const yuangong=reactive({ xingxi:[ {id:1001,name:"张三",sex:"男",birthday:"5-13",site:"湖南",phone:123456212454,"money":1200}, {id:1002,name:"弹起",sex:"男",birthday:"1-23",site:"湖南",phone:123456622224,"money":2300}, {id:1003,name:"赵六",sex:"男",birthday:"2-17",site:"湖南",phone:123456622214,"money":5200}, {id:1004,name:"李四",sex:"女",birthday:"5-13",site:"湖南",phone:123452436654,"money":4200}, {id:1005,name:"王五",sex:"男",birthday:"2-13",site:"湖南",phone:123421221454,"money":1220} ] }) var zongmoney=ref(0) for(var i=0;i<=yuangong.xingxi.length;i++){ zongmoney.value+=yuangong.xingxi[i].money console.log(zongmoney.value) }报错
时间: 2023-07-03 11:22:20 浏览: 153
在 for 循环中,判断条件应该是 `i < yuangong.xingxi.length` 而不是 `i <= yuangong.xingxi.length`,因为数组下标是从 0 开始的,所以当 `i` 等于 `yuangong.xingxi.length` 时,已经超出了数组的索引范围,所以会报错。正确的代码应该是:
```
for (var i = 0; i < yuangong.xingxi.length; i++) {
zongmoney.value += yuangong.xingxi[i].money;
console.log(zongmoney.value);
}
```
相关问题
vue3如何修改reactive中的对象数据 并最后获取该数据
可以通过 Vue3 中的 toRef 和 toRefs 方法将 reactive 对象的属性转化为 ref 对象进行修改,并且最终通过 ref 对象的 value 属性获取修改后的数据。示例代码如下:
```
import { reactive, toRef, toRefs } from "vue";
const state = reactive({
name: "张三",
age: 20,
job: "工程师"
});
// toRef 做法
const nameRef = toRef(state, "name");
nameRef.value = "李四";
// toRefs 做法
const stateRefs = toRefs(state);
stateRefs.name.value = "王五";
console.log(state.name); // "王五"
```
阅读全文