【问题标题】:How to show/manipulate specify values of objects array from backend in Vue?如何在 Vue 中显示/操作从后端指定对象数组的值?
【发布时间】:2020-08-26 09:29:09
【问题描述】:

例如,如果我需要对来自数据库的某个数字(在本例中为 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.js devtools Console errors

存储/模块/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,
    }
}

【问题讨论】:

    标签: javascript laravel vue.js axios vuex


    【解决方案1】:

    你需要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)
    }
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-20
        • 2021-09-25
        • 2021-04-10
        • 2020-11-13
        • 1970-01-01
        • 2020-03-20
        • 2020-07-18
        • 2020-06-08
        相关资源
        最近更新 更多