v-for在VueJS中,如何跟踪以前的组件数据?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了v-for在VueJS中,如何跟踪以前的组件数据?相关的知识,希望对你有一定的参考价值。

我想输出一系列包含值的条目。

但是对于每一行,我想显示从开始到当前行的所有值的总和。

例如:

// App.vue

<template>
    <div>
        <Row v-for="item in items" :value="item.value"/>
    </div>
</template>

<script>
    export default {
        data() {
          items: [{ value: 3}, {value: 5}, {value: 1}, {value: 9}, {value: 3}]
        }
    }
</script>


// Row.vue

<template>
    <div>{{ value }} (Sum: <subtotal here>)</div>
</template>

<script>
    export default {
        props: ['value']
    }
</script>

我想要这个输出:

<div>
    <div>3 (Sum: 3)</div>
    <div>5 (Sum: 8)</div>
    <div>1 (Sum: 9)</div>
    <div>9 (Sum: 18)</div>
    <div>3 (Sum: 21)</div>
</div>

我已经尝试了多种方式,使用Row中的局部变量在App创建/更新上发出事件...

使用本地非反应性变量会在更新组件时导致错误行为。使用prop ou事件会导致无限循环。

我如何逐步累计每个项目值?

答案

使用计算属性为您保留计数:

new Vue({
    el: '#app',
    template: '#template',
    data: {
        items: [{ value: 3}, {value: 5}, {value: 1}, {value: 9}, {value: 3}]
    },
    computed: {
        calculatedItems() {
            const newArray = [];
            let sum = 0;
            for(let i = 0; i < this.items.length; i++) {
                sum += this.items[i].value;
                newArray.push({
                    total: sum,
                    item: this.items[i],
                });
            }
            return newArray;
        },
    },
})
<!-- development version, includes helpful console warnings -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<div id="app"></div>





<template id="template">
    <div>
        <div v-for="item in calculatedItems">
            {{ item.item.value }},
            Total: {{ item.total }}
    </div>
</template>

以上是关于v-for在VueJS中,如何跟踪以前的组件数据?的主要内容,如果未能解决你的问题,请参考以下文章

VueJS 和嵌套的 v-for:如何通过每个循环获取端点数据?

如何从返回的数据组件 vuejs 中拼接一个子数组?

VueJS - 向组件 v-for 添加延迟加载

VueJS:v-for 中的表单 - 如何获取正确的数据?

v-for Vuejs中使用AXIOS时如何调用方法

使用 Vuejs 嵌套 v-for 循环