Files
admin-govern/src/utils/tableStore.ts

119 lines
3.1 KiB
TypeScript
Raw Normal View History

2023-12-22 16:19:33 +08:00
import { reactive } from 'vue'
2023-12-26 16:17:30 +08:00
import createAxios from '@/utils/request'
import { requestPayload } from '@/utils/request'
import { Method } from 'axios'
2023-12-22 16:19:33 +08:00
interface TableStoreParams {
url: string
pk?: string
column: TableColumn[]
params?: anyObj
2023-12-26 16:17:30 +08:00
method?: Method
2023-12-22 16:19:33 +08:00
}
2023-12-26 16:17:30 +08:00
2023-12-22 16:19:33 +08:00
export default class TableStore {
public url
public pk
2023-12-26 16:17:30 +08:00
public method: Method
2023-12-27 10:39:40 +08:00
public initData: any = null
2023-12-22 16:19:33 +08:00
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'
2023-12-26 16:17:30 +08:00
this.method = options.method || 'GET'
2023-12-22 16:19:33 +08:00
this.table.column = options.column
Object.assign(this.table.params, options.params)
}
2023-12-26 16:17:30 +08:00
2023-12-22 16:19:33 +08:00
index() {
2023-12-27 10:39:40 +08:00
// 重置用的数据数据
if (!this.initData) {
this.initData = JSON.parse(JSON.stringify(this.table.params))
}
2023-12-26 16:17:30 +08:00
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
})
2023-12-22 16:19:33 +08:00
}
2023-12-26 16:17:30 +08:00
2023-12-22 16:19:33 +08:00
/**
*
* @param event 事件:selection-change=,page-size-change=,current-page-change=
* @param data
*/
onTableAction = (event: string, data: anyObj) => {
const actionFun = new Map([
2023-12-27 10:39:40 +08:00
[
'search',
() => {
this.table.params.pageNum = 1
this.index()
}
],
[
'reset',
() => {
delete this.initData.pageSize
Object.assign(this.table.params, this.initData)
this.index()
}
],
2023-12-22 16:19:33 +08:00
[
'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)
}
}