index copy.vue
22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
<style lang="scss">
@import './index.scss';
</style>
<template>
<div class="z-schema">
<!-- 头部内容 -->
<div v-if="$scopedSlots.header || $slots.header" class="z-schema__header">
<slot name="header" :filterModel="filterModel" v-bind="_slotScope"></slot>
</div>
<!-- 筛选组件 -->
<div v-if="filter" class="z-schema__filter">
<z-schema-filter
:value="_filterModel"
:list="filterList || listMap.filter | noRulesFilter"
:size="size"
@input="onFilterInput"
@search="onSearch"
:loading="loading"
v-bind="filterProps"
:params="_slotScope"
></z-schema-filter>
</div>
<!-- 按钮区 -->
<div v-if="action" class="z-schema__action">
<slot v-if="hadSlot('action')" name="action" v-bind="_slotScope"></slot>
<template v-else>
<el-button :size="size" type="primary" @click="openNew">新增</el-button>
<el-button :size="size" plain :disabled="selection.length === 0" @click="handleDeleteMul(selection)">删除</el-button>
<slot name="button" v-bind="_slotScope"></slot>
</template>
</div>
<!-- 表格内容 -->
<div class="z-schema__table">
<z-schema-table
ref="table"
v-model="tableData"
v-loading="loading"
:list="tableList || listMap.table"
:tableProps="{ border: true, 'row-key': 'id', 'highlight-current-row': true, ...tableProps }"
:size="size"
@selection-change="onTableSelectionChange"
@selection="onTableSelection"
>
<slot></slot>
<!-- 表格列内容渲染 -->
<template v-for="(item, index) in renderList">
<template v-if="$scopedSlots[`cell-${item.fullKey}`]">
<el-table-column :slot="item.fullKey" v-bind="item" :prop="item.agentKey || item.key" :key="`table-cell-${index}`">
<template slot-scope="{ row, column, $index }">
<slot :name="`cell-${item.fullKey}`" v-bind="{ ...item, ..._slotScope }" :row="row" :value="row[item.key]" :column="column" :index="$index"></slot>
</template>
</el-table-column>
</template>
<template v-else-if="$scopedSlots[`render-${item.fullKey}`]">
<el-table-column :slot="item.fullKey" v-bind="item" :prop="item.agentKey || item.key" :key="`table-render-${index}`">
<template slot-scope="{ row, column, $index }">
<slot :name="`render-${item.fullKey}`" v-bind="{ ...item, ..._slotScope }" :row="row" :value="row[item.key]" :column="column" :index="$index"></slot>
</template>
</el-table-column>
</template>
</template>
<slot slot="column-append" name="column-append" v-bind="_slotScope"></slot>
<!-- 表格尾追加操作列 -->
<template #column-end>
<slot slot="column-end" name="column-end" v-bind="_slotScope"></slot>
<el-table-column v-if="operation" prop="$operation" label="操作" v-bind="{ width: 100, fixed: 'right', ...operationProps }">
<div class="z-schema__table-operation" slot-scope="slotScope">
<slot name="operation-button" v-bind="{ ..._slotScope, slotScope }"></slot>
<el-button type="text" icon="el-icon-edit" title="编辑" @click="openEdit(slotScope.row)"></el-button>
<el-popconfirm confirmButtonText="确定" cancelButtonText="取消" title="确定删除吗?" placement="top" @confirm="handleDelete([slotScope.row])">
<el-button slot="reference" type="text" icon="el-icon-delete" title="删除"></el-button>
</el-popconfirm>
<slot name="operation-button-append" v-bind="{ ..._slotScope, slotScope }"></slot>
</div>
</el-table-column>
</template>
</z-schema-table>
</div>
<!-- 底部区域 -->
<div class="z-schema__footer">
<div v-if="selection.length > 0" class="selection-info">
<span>已选中</span>
<span class="num">{{ selection.length }}</span>
<span>项</span>
<el-popconfirm confirmButtonText="确定" cancelButtonText="取消" title="确定清除吗?" placement="top" @confirm="clearSelection">
<el-button slot="reference" :size="size" type="text">清除</el-button>
</el-popconfirm>
</div>
<!-- 分页器 -->
<el-pagination
v-if="pagination"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="pageSizes"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total"
>
</el-pagination>
</div>
<!-- 弹出框 -->
<el-dialog
:visible.sync="dialogVisible"
:title="dialogTitle"
destroy-on-close
append-to-body
:lock-scroll="false"
:close-on-click-modal="false"
@closed="onDialogClosed"
@close="onDialogClose"
v-bind="_dialogProps"
>
<div v-loading="dialogLoading">
<!-- 自定义弹出框标题 -->
<slot v-if="hadSlot('dialog-title')" slot="title" name="dialog-title" :dialogType="dialogType" v-bind="_slotScope"></slot>
<template v-if="dialogRender">
<!-- 自定义弹出框内容 -->
<slot v-if="hadSlot(`dialog-${dialogType}`)" :name="`dialog-${dialogType}`" :model="_formModel" v-bind="_slotScope"></slot>
<template v-else>
<!-- 内置弹出框新增修改表单 -->
<template v-if="['new', 'edit'].includes(dialogType)">
<z-form
ref="form"
:value="_formModel"
:list="formList || listMap.form"
@input="onFormInput"
@validate="onFormValidate"
v-bind="{ span: 12, 'label-width': '110px', ...formProps }"
:params="_slotScope"
>
<!-- 表单自定义插槽 -->
<template v-for="item in renderList">
<template v-if="$scopedSlots[`form-${item.fullKey}`]">
<slot :slot="item.fullKey" :name="`form-${item.fullKey}`" :value="get(_formModel, item.fullKey)" :row="_formModel" :model="_formModel" v-bind="_slotScope"></slot>
</template>
</template>
</z-form>
</template>
<!-- 内置弹出框详情表单 -->
<template v-else>
<z-form
ref="form"
class="z-schema__view"
:value="_formModel"
:list="viewList || listMap.form | viewTypeFilter | noRulesFilter"
v-bind="{ span: 12, 'label-width': '110px', ...viewProps }"
:params="_slotScope"
>
<!-- 详情自定义插槽渲染 -->
<template v-for="item in renderList">
<template v-if="$scopedSlots[`view-${item.fullKey}`]">
<slot :slot="item.fullKey" :name="`view-${item.fullKey}`" :value="get(_formModel, item.fullKey)" :row="_formModel" :model="_formModel" v-bind="_slotScope"></slot>
</template>
<template v-else-if="$scopedSlots[`render-${item.fullKey}`]">
<slot :slot="item.fullKey" :name="`render-${item.fullKey}`" :value="get(_formModel, item.fullKey)" :row="_formModel" :model="_formModel" v-bind="_slotScope"></slot>
</template>
</template>
</z-form>
</template>
</template>
<!-- 内置弹出框新增修改按钮 -->
<div class="z-schema__dialog-button" v-if="['new', 'edit'].includes(dialogType)">
<el-button :size="size" type="primary" @click="handleConfirm" :loading="submitting">确定</el-button>
<el-button :size="size" plain @click="closeDialog">取消</el-button>
</div>
</template>
</div>
</el-dialog>
</div>
</template>
<script>
import { cloneDeep, get } from '../utils';
import { clear } from '../utils/param';
let propsMap = {};
const propsKeys = ['tableProps', 'filterProps', 'formProps', 'viewProps', 'dialogProps', 'operationProps'];
propsKeys.forEach(key => {
propsMap[key] = {
type: Object,
default: () => ({}),
};
});
const apiKeys = ['searchApi', 'submitApi', 'addApi', 'modifyApi', 'getApi', 'viewApi', 'deleteApi'];
apiKeys.forEach(key => {
propsMap[key] = {
type: Function,
};
});
const blockKeys = ['filter', 'action', 'pagination', 'operation'];
blockKeys.forEach(key => {
propsMap[key] = {
type: Boolean,
default: true,
};
});
export default {
name: 'SchemaPage',
props: {
...propsMap,
list: Array,
filterList: Array,
tableList: Array,
formList: Array,
viewList: Array,
size: {
type: String,
default: 'mini',
},
formModel: Object,
filterModel: Object,
auto: Boolean,
realSelection: Boolean,
url: String, // 请求地址
http: Function, // http库
alias: Object, // 别名配置
},
data() {
return {
filterForm: {},
editForm: {},
dialogVisible: false,
dialogRender: true,
dialogType: 'none',
dialogLoading: false,
dialogTitle: '',
dialogPropsHack: {},
currentPage: 1,
pageSize: 10,
total: 0,
pageSizes: [10, 20, 50],
tableData: [],
submitting: false,
loading: false,
selection: [],
};
},
created() {
if (this.auto) {
this.search();
}
},
filters: {
// 无规则过滤器,过滤掉筛选条件表单中的必填规则等
noRulesFilter(val = []) {
let list = cloneDeep(val);
const clearRules = list => {
list.forEach(item => {
if (item.list) {
clearRules(item.list);
} else {
delete item.rules;
}
});
};
clearRules(list);
return list;
},
// 详情类型过滤器
viewTypeFilter(val = []) {
let list = cloneDeep(val);
const clearRules = list => {
list.forEach(item => {
item.type = (h, { model, config }) => h('span', config, model[item.key]);
});
};
clearRules(list);
return list;
},
},
computed: {
listMap() {
// 默认作用域
const LIST_SPACE = ['filter', 'form', 'table'];
const array = {
filter: [], // 筛选
form: [], // 表单
table: [], // 表格
};
this.list.forEach(item => {
// 可以在列表中通过include或exclude设置当前配置的作用域
const { include = LIST_SPACE, exclude = [] } = item;
// 判断include
let _inclue = [];
if (include instanceof String || typeof include === 'string') {
_inclue = [include];
} else if (include instanceof Array && typeof include === 'object') {
_inclue = include;
}
// 判断exclude转换为include的情况
let _exclude_include = [];
if (exclude instanceof String || typeof exclude === 'string') {
_exclude_include = LIST_SPACE.filter(item => item !== exclude);
} else if (exclude instanceof Array && typeof exclude === 'object') {
_exclude_include = LIST_SPACE.filter(item => !exclude.includes(item));
}
// 作用域交集
const _intersection = _inclue.filter(v => _exclude_include.includes(v));
// 返回改配置项的作用域
const _list_space = cloneDeep(_intersection);
// 将配置项按需分配至各作用域下
_list_space.forEach(name => {
array[name].push({ ...item, ...(item[name] || {}) });
});
});
return array;
},
renderList() {
// 深度克隆传入的列表,避免原始值被修改
const newList = cloneDeep(this.list);
// 生成列表值的全路径key,即列表项为对象时,对象内的key与上一级的key合并作为全路径key
const generateFullKey = (list, parentKey) => {
list.forEach(item => {
if (item.group && item.list) {
if (item.group.key) {
item.fullKey = `${parentKey ? `${parentKey}-${item.group.key}` : item.group.key}`;
} else {
item.fullKey = parentKey || item.key;
}
generateFullKey(item.list, item.fullKey);
} else {
item.fullKey = `${parentKey ? `${parentKey}-${item.key}` : item.key}`;
}
});
};
// 生成fullKey
generateFullKey(newList);
return newList;
},
_filterModel() {
return this.filterModel || this.filterForm || {};
},
_formModel() {
return this.formModel || this.editForm || {};
},
_slotScope() {
return {
handleSearch: this.search,
openDialog: this.openDialog,
closeDialog: this.closeDialog,
openView: this.openView,
openEdit: this.openEdit,
openNew: this.openNew,
handleDelete: this.handleDelete,
handleDeleteMul: this.handleDeleteMul,
size: this.size,
dialogType: this.dialogType,
selection: this.selection,
};
},
_alias() {
const alias = this.alias;
const zAlias = this.zAlias;
if (alias && zAlias) {
return { ...zAlias, ...alias };
}
return this.alias || this.zAlias || {};
},
_dialogProps() {
return {
...this.dialogProps,
...this.dialogPropsHack,
};
},
},
methods: {
get,
// 空Promise
emptyPromise() {
return new Promise(resolve => resolve());
},
// 设置表格选中行
toggleRowSelection() {
this.tableData.forEach(row => {
if (this.selection.find(item => item.id === row.id)) {
this.$refs.table && this.$refs.table.toggleRowSelection(row);
}
});
},
// 表格选中状态
onTableSelectionChange(selection, type) {
if (this.realSelection) {
if (type === 'check') {
const result = this.selection || [];
selection.forEach(item => {
if (!result.find(i => i.id === item.id)) {
result.push(item);
}
});
this.selection = result;
} else if (type === 'uncheck') {
selection.forEach(i => {
this.selection = this.selection.filter(item => item.id !== i.id);
});
}
}
},
// 表格选中
onTableSelection(selection) {
if (!this.realSelection) {
this.selection = selection;
}
},
// 清除表格选中
clearSelection() {
this.$refs.table && this.$refs.table.clearSelection();
this.selection = [];
},
// 内置搜索接口
_searchAPI(params) {
if (this.url && (this.http || this.zHttp)) {
const _http = this.http || this.zHttp;
return _http({ url: `${clear(this.url)}/${this._alias.pageUrl || 'page'}`, params });
}
return undefined;
},
// 重置查询
onSearch() {
this.currentPage = 1;
this.search();
},
// 搜索
async search() {
this.loading = true;
const params = {
...this._filterModel,
currentPage: this.currentPage,
pageSize: this.pageSize,
};
const searchAPI = this.searchApi || this._searchAPI || this.emptyPromise;
await searchAPI(params)
.then(res => {
const response = res || {};
this.tableData = response[this._alias.list || 'list'] || [];
this.total = response[this._alias.total || 'total'] || 0;
this.$nextTick(this.toggleRowSelection);
})
.catch(() => {
this.$message.error('查询失败');
});
this.loading = false;
},
// 更新筛选model
onFilterInput(val) {
this.filterForm = val || {};
this.$emit('update:filterModel', val || {});
},
// 更新表单model
onFormInput(val) {
this.editForm = val || {};
this.$emit('update:formModel', val || {});
},
// 内置新增保存接口
_addAPI(data) {
if (this.url && (this.http || this.zHttp)) {
const _http = this.http || this.zHttp;
return _http({ url: `${clear(this.url)}/${this._alias.addUrl || 'add'}`, method: 'post', data });
}
return undefined;
},
// 内置修改保存接口
_modifyAPI(data) {
if (this.url && (this.http || this.zHttp)) {
const _http = this.http || this.zHttp;
return _http({ url: `${clear(this.url)}/${this._alias.modifyUrl || 'modify'}`, method: 'post', data });
}
return undefined;
},
// 表单提交且通过校验
async onFormValidate(valid, model) {
if (valid) {
this.submitting = true;
let submitAPI = this.submitApi || this.emptyPromise;
if (this.dialogType === 'new') {
submitAPI = this.addApi || this.submitApi || this._addAPI || this.emptyPromise;
} else if (this.dialogType === 'edit') {
submitAPI = this.modifyApi || this.submitApi || this._modifyAPI || this.emptyPromise;
}
submitAPI(model, { type: this.dialogType })
.then(() => {
this.$message.success('保存成功');
this.closeDialog();
this.search();
})
.catch(() => {
this.$message.error('保存失败');
})
.finally(() => {
this.submitting = false;
});
}
},
// 表单按钮确定
handleConfirm() {
this.$refs.form && this.$refs.form.validate();
},
// 表单按钮取消
handleCancel() {
this.closeDialog();
},
// 查询是否有某个插槽
hadSlot(name) {
return !!this.$slots[name] || !!this.$scopedSlots[name];
},
// 打开新增弹出框
openNew() {
this.openDialog('new', '新增');
},
// 内置查询详情接口
_getAPI(row) {
if (this.url && (this.http || this.zHttp)) {
const _http = this.http || this.zHttp;
const _getKey = this._alias.getKey || this._alias.primaryKey || 'id';
const _resultKey = this._alias.result || 'result';
return _http({ url: `${clear(this.url)}/${this._alias.getUrl || 'queryById'}`, params: { [_getKey]: row[_getKey] } }).then(response => response[_resultKey] || {});
}
return undefined;
},
// 打开编辑弹出框
openEdit(row) {
this.dialogLoading = true;
this.openDialog('edit', '编辑');
const getRow = () =>
new Promise(resolve => {
resolve(row);
});
const getAPI = this.getApi || this._getAPI || getRow;
getAPI(row)
.then(result => {
this.editForm = result;
this.$emit('update:formModel', result || {});
})
.finally(() => {
this.dialogLoading = false;
});
},
// 内置查询详情接口
_viewAPI(row) {
if (this.url && (this.http || this.zHttp)) {
const _http = this.http || this.zHttp;
const _viewKey = this._alias.viewKey || this._alias.getKey || this._alias.primaryKey || 'id';
const _resultKey = this._alias.result || 'result';
return _http({ url: `${clear(this.url)}/${this._alias.getUrl || 'queryById'}`, params: { [_viewKey]: row[_viewKey] } }).then(response => response[_resultKey] || {});
}
return undefined;
},
// 打开详情弹出框
openView(row) {
this.dialogLoading = true;
this.openDialog('view', '详情');
const getRow = () =>
new Promise(resolve => {
resolve(row);
});
const viewAPI = this.viewApi || this.getApi || this._viewAPI || this._getAPI || getRow;
viewAPI(row)
.then(result => {
this.editForm = result;
this.$emit('update:formModel', result || {});
})
.finally(() => {
this.dialogLoading = false;
});
},
// 内置删除接口
_deleteAPI(keys) {
if (this.url && (this.http || this.zHttp)) {
const _http = this.http || this.zHttp;
return _http({ url: `${clear(this.url)}/${this._alias.modifyUrl || 'delete'}`, method: 'post', data: keys });
}
return undefined;
},
// 删除
handleDelete(selection) {
const loading = this.$loading({
text: '处理中',
spinner: 'el-icon-loading',
background: 'rgba(255, 255, 255, 0.5)',
});
const deleteAPI = this.deleteApi || this._deleteAPI || this.emptyPromise;
const _deleteKey = this._alias.deleteKey || this._alias.primaryKey || 'id';
const keys = selection.map(i => i[_deleteKey]);
deleteAPI(keys)
.then(() => {
this.search();
this.$message.success('删除成功');
})
.finally(() => {
loading.close();
});
},
// 批量删除
handleDeleteMul(selection) {
this.$confirm(`是否删除这 [${selection.length}] 项?`, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
})
.then(() => {
this.handleDelete(selection);
})
.catch(() => {});
},
// 打开弹出框
openDialog(type, title, config) {
this.dialogVisible = true;
this.dialogRender = true;
this.dialogType = type;
this.dialogTitle = title;
this.dialogPropsHack = config || {};
this.$emit('dialog-change', type);
},
// 关闭弹出框
closeDialog() {
this.dialogVisible = false;
},
// 清空表单
clearEditForm() {
this.editForm = {};
this.$emit('update:formModel', {});
},
// 弹出框关闭
onDialogClose() {
this.dialogType = 'none';
this.dialogRender = false;
this.$emit('dialog-change', 'none');
},
// 弹出框关闭动画结束
onDialogClosed() {
this.clearEditForm();
this.dialogPropsHack = {};
},
// 分页-每页个数
handleSizeChange(val) {
this.pageSize = val;
this.currentPage = 1;
this.$nextTick(this.search);
},
// 分页-当前页数
handleCurrentChange(val) {
this.currentPage = val;
this.$nextTick(this.search);
},
},
};
</script>