Vue.js实现可排序的表格组件功能示例

2020-06-12 21:24:53易采站长站整理

});
trs.push(createElement('tr', tds));
});
return createElement('table', [
createElement('colgroup', cols),
createElement('thead', [
createElement('tr', ths)
]),
createElement('tbody', trs)
])
},
methods: {
//初始化表头
initColumns: function () {
this.currentColumns = this.columns.map(function (col, index) {
//新建字段,标识当前列排序类型;默认为“不排序”
col.sortType = 'normal';
//新建字段,标识当前列在数组中的索引
col.index = index;
return col;
});
},
//初始化数据
initData: function () {
this.currentData = this.data.map(function (row, index) {
//新建字段,标识当前行在数组中的索引
row.index = index;
return row;
});
},
//排序
order: function (index, type) {
this.currentColumns.forEach(function (col) {
col.sortType = 'normal';
});
//设置排序类型
this.currentColumns[index].sortType = type;
//设置排序函数
var sortFunction;
var key = this.currentColumns[index].key;
switch (type) {
default://默认为 asc 排序
case 'asc':
sortFunction = function (a, b) {
return a[key] > b[key] ? 1 : -1;
};
break;
case 'desc':
sortFunction = function (a, b) {
return a[key] < b[key] ? 1 : -1;
};
break;
}
this.currentData.sort(sortFunction);
},
//升序
sortByAsc: function (index) {
this.order(index, 'asc');
},
//降序
sortByDesc: function (index) {
this.order(index, 'desc');
}
},
watch: {
data: function () {
this.initData();
//找出排序字段
var sortedColumn = this.currentColumns.filter(function (col) {
return col.sortType !== 'normal';
});
if (sortedColumn.length > 0) {
if (sortedColumn[0].sortType === 'asc') {
this.sortByAsc(sortedColumn[0].index);
} else {
this.sortByDesc(sortedColumn[0].index);
}
}
}
},
mounted() {
this.initColumns();
this.initData();
}
});
var app = new Vue({
el: '#app',
data: {
//title 、key 与 width 必填;sortable 选填
columns: [
{
title: '名称',
key: 'name',
width:'60%'
},
{
title: '数量',
key: 'num',
width:'20%',
sortable: true