如何在Vue中从后端显示/操作对象数组的指定值



例如,如果我需要对来自数据库的某个数字(在本例中,这些是id(求和,该怎么办?

Laravel/api:

[ 
{ "id": 3, "created_at": null, "updated_at": null, "name": "Name One" }, 
{ "id": 4, "created_at": null, "updated_at": null, "name": "Name Two" } 
]

组件:

<template>
<div class="font-semibold text-4xl text-gray-600">
{{showTotal}}
</div>

import {mapGetters, mapActions} from 'vuex';
export default {
name: "Total",
mounted() {
this.fetchNames();
},
methods: {
...mapActions(["fetchNames"])
},
computed: {
...mapGetters(["getNames"]),
showTotal() {
return this.getNames[0]['id'] + this.getNames[1]['id']
}
},
}

我在控制台中遇到了错误,但在Vue.js devtools中有showTotal:7 Vue.jsdevtools控制台错误

store/modules/names.js:

export default {
state: {
names: [],
},
getters: {
getNames: state => state.names,
},
actions: {
async fetchNames({commit}) {
const response = await axios.get('/api/names');
commit('setNames', response.data);
},
},
mutations: {
setNames: (state, names) => state.names = names,
}
}

您需要reduce来迭代数组

const names = [ 
{ "id": 3, "created_at": null, "updated_at": null, "name": "Name One" }, 
{ "id": 4, "created_at": null, "updated_at": null, "name": "Name Two" } 
]
const total = names.reduce((total, current) => {
return total += current.id;
}, 0)
console.log(total);

所以它将是

showTotal() {
return this.getNames.reduce((total, current) => {
return total += current.id;
}, 0)
}

控制台错误可能是由于this.getNames在第一次呈现组件时返回空数组,而api尚未返回响应,这就是为什么当您尝试访问0索引的id属性时,它会抛出错误。(可能添加一些检查以避免此错误(

您还可以使用forEach尝试一种更简单的添加id的方法。以下代码示例:

showTotal() {
let total = 0;
this.getNames.forEach((item) => total += item.id);
return total;
}

最新更新