Files
admin-govern/src/utils/tableStore.ts
2023-12-27 10:39:40 +08:00

119 lines
3.1 KiB
TypeScript

import { reactive } from 'vue'
import createAxios from '@/utils/request'
import { requestPayload } from '@/utils/request'
import { Method } from 'axios'
interface TableStoreParams {
url: string
pk?: string
column: TableColumn[]
params?: anyObj
method?: Method
}
export default class TableStore {
public url
public pk
public method: Method
public initData: any = null
public table: CnTable = reactive({
ref: null,
selection: [],
data: [],
total: 0,
params: {
pageNum: 1,
pageSize: 10
},
loading: true,
column: []
})
constructor(public options: TableStoreParams) {
this.url = options.url
this.pk = options.pk || 'id'
this.method = options.method || 'GET'
this.table.column = options.column
Object.assign(this.table.params, options.params)
}
index() {
// 重置用的数据数据
if (!this.initData) {
this.initData = JSON.parse(JSON.stringify(this.table.params))
}
createAxios(
Object.assign(
{
url: this.url,
method: this.method
},
requestPayload(this.method, this.table.params)
)
).then((res: any) => {
this.table.data = res.data.records || res.data
this.table.total = res.data.total || res.data.length
this.table.loading = false
})
}
/**
* 表格内的事件统一响应
* @param event 事件:selection-change=选中项改变,page-size-change=每页数量改变,current-page-change=翻页
* @param data 携带数据
*/
onTableAction = (event: string, data: anyObj) => {
const actionFun = new Map([
[
'search',
() => {
this.table.params.pageNum = 1
this.index()
}
],
[
'reset',
() => {
delete this.initData.pageSize
Object.assign(this.table.params, this.initData)
this.index()
}
],
[
'selection-change',
() => {
this.table.selection = data as TableRow[]
}
],
[
'page-size-change',
() => {
this.table.params!.pageSize = data.size
}
],
[
'current-page-change',
() => {
this.table.params!.pageNum = data.page
this.index()
}
],
[
'field-change',
() => {
console.warn('field-change')
}
],
[
'default',
() => {
console.warn('No action defined')
}
]
])
const action = actionFun.get(event) || actionFun.get('default')
action!.call(this)
}
}