一、avue-crud
1、avue版本须为2.9.0+
2、导入需要的包 (放到index.html中的head标签里)
<script src="https://cdn.staticfile.org/Sortable/1.10.0-rc2/Sortable.min.js"></script>
3、重要配置 columnSort:true
4、确保配置的column数组中,列属性无hide:true,因为我有新增编辑功能,必须要设置一些列隐藏,所以将隐藏的对象统一放在最后,不影响前面列的拖拽排序(这里我试了,设置了某列隐藏,该列及及之后的列都不能拖拽,但前面的列拖拽不影响)
代码如下:
<template>
<avue-crud :option="option" :data="data"></avue-crud>
</template>
<script>
export default {
data(){
return {
data:[{
text1:'内容1-1',
text2:'内容1-2',
text3:'内容1-3'
},{
text1:'内容2-1',
text2:'内容2-2',
text3:'内容2-3'
},{
text1:'内容3-1',
text2:'内容3-2',
text3:'内容3-3'
}],
option:{
columnSort:true,
column: [{
label: '列内容1',
prop: 'text1',
}, {
label: '列内容2',
prop: 'text2',
}, {
label: '列内容3',
prop: 'text3',
hide: true,
}]
}
}
}
}
</script>
二、vxe-grid
1、必须加columnKey ,否则拖拽后数据移动成功但表头未改变
代码如下:
<template>
<vxe-grid ref="xGrid" :columns="column" columnKey :data="data"></vxe-grid>
</template>
<script>
export default {
name: 'test',
data() {
return {
data: [{
text1: '内容1-1',
text2: '内容1-2',
text3: '内容1-3'
}, {
text1: '内容2-1',
text2: '内容2-2',
text3: '内容2-3'
}, {
text1: '内容3-1',
text2: '内容3-2',
text3: '内容3-3'
}],
column: [{
title: '列内容1',
field: 'text1',
}, {
title: '列内容2',
field: 'text2',
}, {
title: '列内容3',
field: 'text3'
}]
};
},
created() {
this.columnDrop();
},
methods: {
columnDrop() {
this.$nextTick(() => {
const $table = this.$refs.xGrid;
this.sortableVxe = Sortable.create(
$table.$el.querySelector(
'.body--wrapper>.vxe-table--header .vxe-header--row'
),
{
handle: '.vxe-header--column:not(.col--fixed)',
onEnd: ({item, newIndex, oldIndex}) => {
const {fullColumn, tableColumn} = $table.getTableColumn();
const targetThElem = item;
const wrapperElem = targetThElem.parentNode;
const newColumn = fullColumn[newIndex];
if (newColumn.fixed) {
// 错误的移动
if (newIndex > oldIndex) {
wrapperElem.insertBefore(
targetThElem,
wrapperElem.children[oldIndex]
);
} else {
wrapperElem.insertBefore(
wrapperElem.children[oldIndex],
targetThElem
);
}
return this.$XModal.message({
content: '固定列不允许拖动!',
status: 'error',
});
}
// 转换真实索引
const oldColumnIndex = $table.getColumnIndex(
tableColumn[oldIndex]
);
const newColumnIndex = $table.getColumnIndex(
tableColumn[newIndex]
);
// 移动到目标列
const currRow = fullColumn.splice(oldColumnIndex, 1)[0];
fullColumn.splice(newColumnIndex, 0, currRow);
$table.loadColumn(fullColumn);
},
}
);
});
},
}
};
</script>