console
const datas = [{
id: 1,
title: 'test1',
content: 'test conent2'
}, {
id: 2,
title: 'test3',
content: 'test conent4'
}, {
id: 3,
title: 'test2',
content: 'test conent1'
}, {
id: 4,
title: 'test4',
content: 'test conent3'
}];
var sortTable = Vue.extend({
template: `<table>
<thead>
<tr>
<th v-for='(key, value) in datas[0]' @click='sortByKey(key)'>{{key}}<i class="sort" :class="{ 'inc': inc && sortKey == key, 'desc': !inc && sortKey == key}"></i></th>
</tr>
</thead>
<tbody>
<tr v-for="item in datas | sortedData">
<td v-for='value in item'>{{value}}</td>
</tr>
</tbody>
</table>
`,
props:['datas'],
data: function() {
return {
sortKey: '',
inc: true
}
},
filters: {
sortedData: function(arr) {
let inc = this.inc,
sortKey = this.sortKey;
if (!sortKey)
return arr.slice();
return arr.slice().sort(function(a, b) {
return inc ? a[sortKey] > b[sortKey] : a[sortKey] < b[sortKey];
});
}
},
methods: {
sortByKey: function(key) {
this.sortKey = key;
this.inc = !this.inc;
}
}
});
var app = new Vue({
el:'#app',
data: {
datas: datas
},
components: {
'sortable-table': sortTable
}
});
<div id="app">
<sortable-table v-bind:datas='datas'></sortable-table>
</div>
* {
box-sizing:border-box;
}
body {
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #333;
}
table {
border-spacing: 0;
border: 1px solid #ddd;
}
td,th {
padding: 8px;
line-height: 1.42857143;
vertical-align: top;
}
td {
border-top: 1px solid #ddd;
}
th {
cursor: pointer;
}
.sort {
position:relative;
left:3px;
}
.sort::before,.sort::after {
content: '';
position:relative;
display:inline-block;
border:5px solid rgba(0,0,0,0);
box-sizing:content-box;
width:0;
height:0;
}
.sort::before {
top:-6px;
border-bottom-color:#000;
}
.sort::after {
top: 6px;
left:-10px;
border-top-color:#000;
}
.sort.desc::before {
border-bottom-color:rgba(0, 0, 0, 0.2);
}
.sort.inc::after {
border-top-color:rgba(0, 0, 0, 0.2);
}