#vue.js
#vue.js
Вопрос:
Я пытаюсь отсортировать данные таблицы HTML на основе щелчка заголовка таблицы в строке таблицы, используя Vue JS 2.
Я реализовал сортировку 1-го столбца. Однако по какой-то причине, возможно, из-за какой-то проблемы с синтаксисом, сортировка по остальным столбцам не работает.
В HTML параметры функции сортировки кажутся мне проблематичными.
<th v-for="(toolAttribute, index) in results.toolAttribute" :key="index" @click="sort('info.value')" class="header">{{toolAttribute.attributeName}}</th>
То, что нужно посмотреть в файле JS:
computed:{
sortedResults:function() {
return this.results.device.sort(function(a,b){
let modifier = 1;
if(this.currentSortDir === 'desc') modifier = -1;
if(a[this.currentSort] < b[this.currentSort]) return -1 * modifier;
if(a[this.currentSort] > b[this.currentSort]) return 1 * modifier;
return 0;
}.bind(this));
}
}
В частности:
return this.results.device.sort(function(a,b)
Вот скрипка для того же:
Комментарии:
1. Я думаю, вы можете легко использовать компонент DataTable, предоставляемый Vuetify. Вот ссылка .
2. Кажется, это было бы значительным переписыванием кода с помощью Vuetify
3. пожалуйста, определите, что стоит на первом месте?
[{value: false}, {value: false}, {value: false}] or [{value: true}, {value: false}, {value: true}]
, в вашем текущем примере это не определено
Ответ №1:
У вас есть какое-то неопределенное поведение, переходящее info.value
в {info:[{value: true}, ...]}
исправление этого путем передачи массивов:
sort(['deviceName'])
или
sort(['info', index, 'value'])
и в Array.sort
методе выполняет итерацию и самостоятельно присваивает переданные значения:
function(a,b){
let modifier = 1;
if(this.currentSortDir === 'desc') modifier = -1;
this.currentSort.forEach(x => {
a = a[x];
b = b[x];
})
if(a< b) return -1 * modifier;
if(a > b) return 1 * modifier;
return 0;
}
решение:
new Vue({
el: '#app',
data: {
results: {
toolAttribute: [{attributeName: "Present"},{attributeName: "Present"},{attributeName: "Present"}],
device: [
{deviceName: "Device Name 1",
info: [{value: true}, {value: false}, {value: true}]},
{deviceName: "Device Name 2",
info: [{value: false}, {value: false}, {value: false}]},
{deviceName: "Device Name 3",
info: [{value: true}, {value: true}, {value: true}]},
{deviceName: "Device Name 4",
info: [{value: false}, {value: true}, {value: false}]},
{deviceName: "Device Name 5",
info: [{value: true}, {value: true}, {value: true}]}
]
},
currentSort:['deviceName'],
currentSortDir:'asc'
},
computed:{
sortedResults:function() {
return this.results.device.sort(function(a,b){
let modifier = 1;
if(this.currentSortDir === 'desc') modifier = -1;
this.currentSort.forEach(x => {
a = a[x];
b = b[x];
})
if(a< b) return -1 * modifier;
if(a > b) return 1 * modifier;
return 0;
}.bind(this));
}
},
methods:{
flasecond(index){
let res = false
this.results.device[index].info.forEach(info=> {
if(!info.value) res = true
})
return res
},
sort:function(s) {
//if s == current sort, reverse
if(s.join('') === this.currentSort.join('')) {
this.currentSortDir = this.currentSortDir==='asc'?'desc':'asc';
}
this.currentSort = s;
},
}
})
.falseclass{
background:red;
color:white;
}
.header {
cursor: pointer;
}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<table >
<tr>
<th rowspan="2" @click="sort(['deviceName'])" class="header">Device Info</th>
</tr>
<tr>
<th v-for="(toolAttribute, index) in results.toolAttribute" :key="index" @click="sort(['info', index, 'value'])" class="header">{{toolAttribute.attributeName}}</th>
</tr>
<tr v-for="(device, index) in sortedResults" >
<td :class="{'falseclass' : flasecond(index)}">{{ device.deviceName }}</td>
<td v-for="info in device.info" :class="{'falseclass' : !info.value}">{{info.value}}</td>
</tr>
</table>
</div>
Комментарии:
1. Как можно добавить сюда значки font awesome на основе направления asc или desc?
2. Как и любой компонент — v-if asc v-else-if desc и т. Д
3. Это показывает значки asc / desc для каждого столбца, что означает, что здесь чего-то не хватает
4. И оба значка должны быть там по умолчанию.