Answer the question
In order to leave comments, you need to log in
How to properly show best and worst value in Vue table?
Hello, there is an array of data, where there is a value of speed and time. It is necessary to show in the plate the smallest value of time and the largest value of speed; if the values are equal, then select both options. The algorithm itself is not a problem, I wrote it and it looks like this. When the method is called , the set
array is first processed, the best values are allocated, and then the array is changed. I know that the code is not written optimally, because this is just an example The essence of the question is how to do it right in Vue? There are directives, computed properties. Is there any better solution to this problem?
Code below:
var table = new Vue({
el: '#app-4',
template: `
<div v-if="visible" id="sumTable">
<table id="dataTable">
<tbody>
<tr v-for="(competitor,index) in competitors">
<td>{{competitor.start}}<span style="color:red" v-if="bestOf.start[index]">★</span></td>
<td>{{competitor.speed}}<span style="color:red" v-if="bestOf.speed[index]">★</span></td>
</tr>
</tbody>
</table></div>`,
data: {
visible: false,
competitors: [{
start: '',
speed: '',
}],
bestOf: {
start: {},
speed: {},
}
},
created: function () {
window.addEventListener('keyup', this.tableVisible)
},
methods: {
tableVisible: function (event) {
if (event.keyCode === 88) {
this.visible = !this.visible;
if (this.visible) {
window.calculateRaceStatsTable()
}
}
},
set: function (newArray) {
newArray.data.forEach(function(competitor,index,array){
if (!this.bestOf['start'].value || this.bestOf['start'].value > parseFloat(competitor['start'])){
this.bestOf['start'] = {};
Vue.set(this.bestOf['start'],'value',parseFloat(competitor['start']))
Vue.set(this.bestOf['start'],index,true)
} else if (this.bestOf['start'].value === parseFloat(competitor['start'])) {
Vue.set(this.bestOf['start'],index,true)
}
if (!this.bestOf['speed'].value || this.bestOf['speed'].value < parseFloat(competitor['speed'])){
this.bestOf['speed'] = {};
Vue.set(this.bestOf['speed'],'value',parseFloat(competitor['speed']))
Vue.set(this.bestOf['speed'],index,true)
} else if (this.bestOf['speed'].value === parseFloat(competitor['speed'])) {
Vue.set(this.bestOf['speed'],index,true)
}
}.bind(this))
this.competitors = newArray.data.slice()
}
}
})
Answer the question
In order to leave comments, you need to log in
We make the calculated properties of the minimum and maximum:
computed: {
minStart() {
return Math.min(...this.competitors.map(n => n.start));
},
maxSpeed() {
return Math.max(...this.competitors.map(n => n.speed));
},
},
<tr v-for="{ start, speed } in competitors">
<td :class="{ best: start === minStart }">{{ start }}</td>
<td :class="{ best: speed === maxSpeed }">{{ speed }}</td>
</tr>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question