/**
* 通用多列排序 Mixin
* 用法:在页面 data() 中声明 sortableColumns,在 loadList() 中加入 sortParams,
* 在 el-table-column 的 slot="header" 中调用 this.sortHeader(col)。
*/
export default {
data() {
return {
sortState: [], // [{column, order:'asc'|'desc'}]
}
},
computed: {
sortLabel() {
if (!this.sortState || this.sortState.length === 0) return ''
const labels = this.sortableColumns || {}
return this.sortState.map(s => {
const label = labels[s.column] || s.column
return (s.order === 'asc' ? label + '↑' : label + '↓')
}).join(' > ')
}
},
methods: {
/**
* 渲染排序列头 HTML 字符串(供 slot 内联使用)
* 用法:
*/
sortHeader(col, label) {
const icon = this.sortIcon(col)
const cls = this.sortClass(col)
const safeCol = col.replace(/[."']/g, '')
return ``
},
sortClass(col) {
const s = this.sortState.find(x => x.column === col)
if (!s) return ''
return s.order === 'asc' ? 'sort-asc' : 'sort-desc'
},
sortIcon(col) {
const s = this.sortState.find(x => x.column === col)
if (!s) return ''
return s.order === 'asc' ? ' ↑' : ' ↓'
},
onSortClick(col, event) {
if (event.shiftKey) {
this.shiftAppendSort(col)
} else {
this.setPrimarySort(col)
}
if (typeof this.loadList === 'function') this.loadList()
},
onSortToggle(col) {
const idx = this.sortState.findIndex(s => s.column === col)
if (idx >= 0) {
this.sortState[idx].order = this.sortState[idx].order === 'asc' ? 'desc' : 'asc'
} else {
this.sortState = [{ column: col, order: 'asc' }]
}
if (typeof this.loadList === 'function') this.loadList()
},
setPrimarySort(col) {
const idx = this.sortState.findIndex(s => s.column === col)
if (idx >= 0) {
const item = this.sortState.splice(idx, 1)[0]
this.sortState.unshift(item)
} else {
this.sortState = [{ column: col, order: 'asc' }]
}
},
shiftAppendSort(col) {
const idx = this.sortState.findIndex(s => s.column === col)
if (idx >= 0) {
this.sortState[idx].order = this.sortState[idx].order === 'asc' ? 'desc' : 'asc'
} else if (this.sortState.length < 3) {
this.sortState.push({ column: col, order: 'asc' })
}
},
clearSort() {
this.sortState = []
if (typeof this.loadList === 'function') this.loadList()
},
/** 将当前 sortState 注入到请求参数中 */
applySortToParams(params) {
if (this.sortState.length > 0) {
params.sort = this.sortState
}
return params
}
}
}