by marksomnian · 3y ago · 0 comments
const items = [];
let runningTotal = 0;
for (const item of someArray) {
runningTotal += item;
items.push(<li>Item {item}; running total {runningTotal}</li>);
}
return (<ul>{items}</ul>);
The closest example I can find in Vue would require a computed property to implement something like this. <script setup>
const items = [1,2,3,4,5,6]
let runningTotal = 0
const getRunningTotal = (item) => {
runningTotal += item
return runningTotal
}
</script>
<template>
<ul>
<li v-for="item in items">
Item {{item}}; running total {{ getRunningTotal(item) }}
</li>
</ul>
</template>
No need for a computed property. Plus, getRunningTotal can be unit tested, or extracted to another file for reusability.If you're after keeping the concerns separate you would need to precompute the running total for each item.
See also: mustache(5) which completely embodies this philosophy.
It is just that above example is so short and readable, that you don't have to bother.
return (
<ul>
{someArray.map((item, idx) => (
<li key={item.id}>Item {item}; running total {idx + 1}</li>
)}
</ul>
);