我正在使用vue-cli,并且试图找出如何更新模板中的计数器:
<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>
我希望根据警告数组中有多少警报来为每个用户更新计数器:
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',}]
},
]
所以输出应如下所示:
Ray Mike
Count:2 Count:1
任何帮助将不胜感激,谢谢!
我用过:
this.outerArray[index].warning.length
显示警告中有多少警报。
答案 0 :(得分:1)
如果此值仅在项目之间更改,则:
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>