Reputation: 91
I'm using vue-cli and I'm trying to figure out how to update counter in my template:
<div v-for="(item, index) in outerArray" :key="item.id" v-bind:id="item.name">
<div> <p> {{ item.name }}</p> </div>
<div>Count:{{count}}</div>
I would like the counter to update for each user based off of how many alerts are in warning array:
outerArray:[
{ name: 'Ray',
count: null,
warning: [{time: '2:00', alert: 'G: 150',},
{time: '7:00', alert: 'RR: 38',}]
},
{ name: 'Mike',
count: null,
warning:[{time: '9:00',alert: 'G: 40',}]
},
]
So the output should look like:
Ray Mike
Count:2 Count:1
Any help would be appreciated, thanks!
I used:
this.outerArray[index].warning.length
to display how many alerts were in warnings.
Upvotes: 0
Views: 597
Reputation: 8329
If this value only changes from item to item, then:
new Vue({
el: "#app",
data: {
outerArray: [{
name: 'Ray',
count: null,
warning: [{
time: '2:00',
alert: 'G: 150',
},
{
time: '7:00',
alert: 'RR: 38',
}
]
},
{
name: 'Mike',
count: null,
warning: [{
time: '9:00',
alert: 'G: 40',
}]
},
]
},
methods: {
countWarnings(item) {
return item.warning.length
}
},
mounted() {
this.outerArray.forEach(e => {
e.count = e.warning.length
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(item, index) in outerArray" :key="item.id" v-bind:id="item.name">
<div>
<p>{{ item.name }}</p>
</div>
<div>Count (from item.warning): {{ item.warning.length }}</div>
<div>Count (with item.count set at mounted): {{ item.count }}</div>
<div>Count (with a count method): {{ countWarnings(item) }}</div><br />
If you're not sure, what a variable holds, you can either use the Vue extension (in Chrome), the console or the screen:<br />
- The item is: {{ item }}<br />
- The item.warning is: {{ item.warning }}<br />
- The item.warning.length is: {{ item.warning.length }}
<br />
<hr />
</div>
</div>
Upvotes: 2