index.vue 19.1 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
<style lang="scss">
@import './index.scss';
</style>

<template>
  <div class="eagle-schema-page">
    <!-- 头部内容 -->
    <div v-if="getSlot('header')" class="eagle-schema-page__header">
      <slot name="header" v-bind="_slotScope"></slot>
    </div>
    <!-- 筛选组件 -->
    <div v-if="schema.filter" class="eagle-schema-page__filter">
      <eagle-schema-filter :size="_size" :schema="schema.filter" :value="valueFilter" @input="e => $emit('update:value-filter', e)" :loading="tableLoading" @search="onSearch">
        <template v-for="item in getSlotKeys('filter-')" #[item.name]="slotScope">
          <slot :name="item.slot" v-bind="{ ..._slotScope, ...slotScope }"></slot>
        </template>
      </eagle-schema-filter>
    </div>
    <!-- 按钮区 -->
    <div v-if="schema.action !== false" class="eagle-schema-page__action">
      <slot name="action" v-bind="_slotScope">
        <el-button :size="_size" type="primary" @click="openNew">新增</el-button>
        <el-button v-if="schema.selection !== false" :size="_size" plain :disabled="selection.length === 0" @click="onDeleteMultiple(selection)">删除</el-button>
        <slot name="action-button" v-bind="_slotScope"></slot>
      </slot>
    </div>
    <!-- 表格内容 -->
    <div v-if="schema.table || $scopedSlots.table" class="eagle-schema-page__table">
      <slot name="table" v-bind="_slotScope">
        <eagle-schema-table
          :size="_size"
          :schema="tableSchemaDefaultProps(schema.table)"
          :value="datagrid ? datagridData : tableData"
          v-loading="schema.loading !== false ? tableLoading : false"
          @selection-change="onTableSelectionChange"
          @input="onTableInput"
        >
          <template #left>
            <el-table-column v-if="schema.selection !== false" type="selection" width="40" align="center"></el-table-column>
          </template>
          <template v-for="item in getSlotKeys('table-')" #[item.name]="slotScope">
            <slot :name="item.slot" v-bind="{ ..._slotScope, ...slotScope }"></slot>
          </template>
          <slot v-if="schema.operation !== false" name="operation" v-bind="_slotScope">
            <el-table-column v-bind="{ label: '操作', width: '90', align: 'center', ...(schema.operation || {}) }">
              <template #default="{ row, column, $index }">
                <div class="eagle-schema-page__table-operation">
                  <slot name="operation-left" v-bind="{ ..._slotScope, row, column, $index }"></slot>
                  <slot name="operation-button" v-bind="{ ..._slotScope, row, column, $index }"></slot>
                  <el-button type="text" icon="el-icon-edit" title="编辑" @click="openEdit(row)"></el-button>
                  <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" title="确定删除吗?" placement="top" @confirm="onDelete([row])">
                    <el-button slot="reference" type="text" icon="el-icon-delete" title="删除"></el-button>
                  </el-popconfirm>
                  <slot name="operation-right" v-bind="{ ..._slotScope, row, column, $index }"></slot>
                </div>
              </template>
            </el-table-column>
          </slot>
        </eagle-schema-table>
      </slot>
    </div>
    <!-- 底部区域 -->
    <div v-if="!datagrid && (schema.selection !== false || schema.pagination !== false || $scopedSlots.footer)" class="eagle-schema-page__footer">
      <slot name="footer" v-bind="_slotScope">
        <div v-if="schema.selection !== false && selection.length > 0" class="selection-info">
          <span>已选中</span>
          <span class="num">{{ selection.length }}</span>
          <span>项</span>
        </div>
        <!-- 分页器 -->
        <slot v-if="schema.pagination !== false" name="pagination" v-bind="_slotScope">
          <el-pagination
            :size="_size"
            @size-change="onSizeChange"
            @current-change="onCurrentChange"
            :current-page="currentPage"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            :layout="layout"
            :total="total"
            v-bind="schema.pagination"
          >
          </el-pagination>
        </slot>
      </slot>
    </div>
    <!-- 弹出框 -->
    <el-drawer :visible="_modalComponent === 'el-drawer' && visible" v-bind="_drawerProps" v-on="_modalListeners">
      <template v-for="item in getSlotKeys('dialog-')" #[item.name]="slotScope">
        <slot :name="item.slot" v-bind="{ ..._slotScope, ...slotScope }"></slot>
      </template>
      <template v-if="_modalComponent === 'el-drawer' && modalRender">
        <div v-loading="dialogLoading" class="eagle-schema-page__drawer-content" :style="`height: calc(100vh - ${getSlot(`dialog-${modalType}-footer`) ? 115 : 55}px);`">
          <slot :name="`dialog-${modalType}`" v-bind="_slotScope"></slot>
        </div>
        <div v-if="getSlot(`dialog-${modalType}-footer`)" class="eagle-schema-page__drawer-footer">
          <slot :name="`dialog-${modalType}-footer`" v-bind="_slotScope"></slot>
        </div>
      </template>
    </el-drawer>
    <el-dialog :visible="_modalComponent === 'el-dialog' && visible" v-bind="_dialogProps" v-on="_modalListeners">
      <template v-for="item in getSlotKeys('dialog-')" #[item.name]="slotScope">
        <slot :name="item.slot" v-bind="{ ..._slotScope, ...slotScope }"></slot>
      </template>
      <!-- 弹出框内容渲染状态,用于关闭时销毁已渲染的内容 -->
      <div v-if="_modalComponent === 'el-dialog' && modalRender" v-loading="dialogLoading">
        <!-- 自定义弹出框内容 -->
        <slot v-if="getSlot(`dialog-${modalType}`)" :name="`dialog-${modalType}`" v-bind="_slotScope"></slot>
        <template v-else>
          <!-- 新增/修改弹出框内容 -->
          <template v-if="['new', 'edit'].includes(modalType)">
            <template v-if="schema.form">
              <eagle-schema-form
                :key="`form-${modalType}`"
                ref="form"
                :size="_size"
                :value="valueForm"
                @input="e => $emit('update:value-form', e)"
                :schema="schema.form"
                @submit="onFormSubmit"
                @cancel="closeDialog"
              >
                <template v-for="item in getSlotKeys('form-')" #[item.name]="slotScope">
                  <slot :name="item.slot" v-bind="{ ..._slotScope, ...slotScope }"></slot>
                </template>
                <template #footer="{ submit, cancel }">
                  <div style="text-align: center; width: 100%">
                    <el-button :size="_size" type="primary" @click="submit" :loading="submitting">确定</el-button>
                    <el-button :size="_size" plain @click="cancel">取消</el-button>
                  </div>
                </template>
              </eagle-schema-form>
            </template>
          </template>
          <!-- 详情弹出框内容 -->
          <template v-else-if="modalType === 'detail'">
            <template v-if="schema.form || schema.detail">
              <eagle-schema-form key="form-detail" ref="form" v-model="detail" :size="_size" :schema="schema.detail || detailSchema">
                <template v-for="item in getSlotKeys('detail-')" #[item.name]="slotScope">
                  <slot :name="item.slot" v-bind="{ ..._slotScope, ...slotScope }"></slot>
                </template>
              </eagle-schema-form>
            </template>
          </template>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep, get } from '../utils';
import { filterout } from '../utils/schema';
import MIX_ORGIN from '../mixins/origin';

let propsMap = {};

const setKeysDefault = function(keys, value) {
  keys.reduce(function(result, current) {
    result[current] = value;
    return result;
  }, propsMap);
};
setKeysDefault(['value-filter', 'value-form', 'value-detail'], {
  type: Object,
  default() {
    return {};
  },
});
setKeysDefault(['value-table'], {
  type: Array,
  default() {
    return [];
  },
});
setKeysDefault(['size', 'dialogTitle', 'dialogType'], String);
setKeysDefault(['dialogVisible', 'auto', 'loading', 'datagrid'], Boolean);
setKeysDefault(['tips'], {
  type: Boolean,
  default: true,
});
setKeysDefault(['api-search', 'api-submit', 'api-new', 'api-edit', 'api-get', 'api-detail', 'api-delete'], Function);

export default {
  name: 'SchemaPage',
  mixins: [MIX_ORGIN],
  props: {
    ...propsMap,
    schema: {
      required: true,
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      selection: [],
      // 分页参数
      currentPage: get(this.schema, 'pagination.currentPage') || 1,
      pageSizes: get(this.schema, 'pagination.pageSizes') || [10, 20, 50, 100],
      pageSize: get(this.schema, 'pagination.pageSize') || 10,
      layout: get(this.schema, 'pagination.layout') || 'total, sizes, prev, pager, next, jumper',
      total: get(this.schema, 'pagination.total') || 0,
      visible: this.dialogVisible,
      modalRender: true,
      modalType: this.dialogType || 'none',
      modalTitle: this.dialogTitle || '',
      modalProps: {},
      detailSchema: filterout(cloneDeep(this.schema.form || {}), ['is', 'rules']),
      detail: this.valueDetail || {},
      tableData: this.valueTable || [],
      tableLoading: this.loading || false,
      submitting: false,
      dialogLoading: false,
    };
  },
  created() {
    if (this.auto || this.schema.auto) {
      this.onSearch();
    }
  },
  watch: {
    valueDetail(val) {
      this.detail = val;
    },
    detail(val) {
      this.$emit('update:value-detail', val);
    },
    dialogVisible(val) {
      this.visible = val;
    },
    visible(val) {
      this.$emit('update:dialog-visible', val);
    },
    dialogType(val) {
      this.modalType = val;
    },
    modalType(val) {
      this.$emit('update:dialog-type', val);
    },
    dialogTitle(val) {
      this.modalTitle = val;
    },
    modalTitle(val) {
      this.$emit('update:dialog-title', val);
    },
    valueTable(val) {
      this.tableData = val;
    },
    tableData(val) {
      this.$emit('update:value-table', val);
    },
    tableLoading(val) {
      this.$emit('update:loading', val);
    },
  },
  computed: {
    slotKeys() {
      return Object.keys(this.$scopedSlots);
    },
    _size() {
      return this.size || get(this.schema, 'props.size') || (this.$ELEMENT || {}).size;
    },
    _slotScope() {
      const properties = ['selection', 'currentPage', 'pageSizes', 'pageSize', 'layout', 'total'];
      const methods = [
        'search',
        'onSearch',
        'onDelete',
        'onDeleteMultiple',
        'onSizeChange',
        'onCurrentChange',
        'onTableSelectionChange',
        'openNew',
        'openEdit',
        'openDetail',
        'openDialog',
        'closeDialog',
      ];
      const defaultScope = {
        size: this._size,
        loading: this.tableLoading,
      };
      return [...properties, ...methods].reduce((result, current) => {
        result[current] = this[current];
        return result;
      }, defaultScope);
    },
    _dialogProps() {
      const { is, ...other } = this.modalProps || {};
      return {
        title: this.modalTitle,
        'lock-scroll': false,
        'append-to-body': true,
        'destroy-on-close': true,
        'close-on-click-modal': false,
        ...(this.schema.dialog || {}),
        ...other,
      };
    },
    _drawerProps() {
      const { is, ...other } = this.modalProps || {};
      return {
        title: this.modalTitle,
        size: '50%',
        'append-to-body': true,
        'destroy-on-close': true,
        'close-on-click-modal': false,
        'custom-class': 'eagle-schema-page__drawer',
        ...(this.schema.drawer || {}),
        ...other,
      };
    },
    _modalComponent() {
      if (this.modalProps.is === 'el-drawer') {
        return 'el-drawer';
      }
      return 'el-dialog';
    },
    _modalListeners() {
      return {
        'update:visible': this.onVisibleUpdate,
        close: this.onDialogClose,
        closed: this.onDialogClosed,
      };
    },
    datagridData() {
      return this.tableData.map((row, index) => {
        return { ...row, $index: index };
      });
    },
  },
  methods: {
    tableSchemaDefaultProps(val) {
      const config = cloneDeep(val);
      const defaultProps = { border: true, 'highlight-current-row': true };
      if (config.props) {
        return { ...config, props: { ...defaultProps, ...config.props } };
      } else {
        return { ...config, props: defaultProps };
      }
    },
    getSlot(name) {
      return this.$slots[name] || this.$scopedSlots[name];
    },
    getSlotKeys(prefix) {
      return this.slotKeys.reduce((result, current) => {
        if (current.indexOf(prefix) === 0) {
          result.push({
            slot: current,
            name: current.substring(prefix.length),
          });
        }
        return result;
      }, []);
    },
    // 空Promise
    emptyPromise() {
      return new Promise(resolve => resolve());
    },
    // 查询
    search() {
      if (this.datagrid) {
        return;
      }
      if (!this.tableLoading) {
        this.tableLoading = true;
        const params = {
          ...this.valueFilter,
          currentPage: this.currentPage,
          pageSize: this.pageSize,
        };
        const searchAPI = this.apiSearch || this.emptyPromise;
        searchAPI(params)
          .then(res => {
            const response = res || [];
            this.tableData = response[0] || [];
            this.total = response[1] || 0;
          })
          .finally(() => {
            this.tableLoading = false;
          });
      }
    },
    // 表格数据改变
    onTableInput(value) {
      if (!this.datagrid) {
        this.tableData = value;
      }
    },
    // 重置查询
    onSearch() {
      this.currentPage = 1;
      this.search();
    },
    // 表单提交
    onFormSubmit(value) {
      if (this.$listeners['form-submit']) {
        this.$emit('form-submit', value);
      } else {
        this.submitting = true;
        let submitAPI = this.apiSubmit || this.emptyPromise;
        if (this.modalType === 'new') {
          submitAPI = this.apiNew || this.apiSubmit || this.emptyPromise;
          if (this.datagrid) {
            submitAPI = () => {
              return new Promise(resolve => {
                this.tableData.push(value);
                resolve();
              });
            };
          }
        } else if (this.modalType === 'edit') {
          submitAPI = this.apiEdit || this.apiSubmit || this.emptyPromise;
          if (this.datagrid) {
            submitAPI = () => {
              return new Promise(resolve => {
                const { $index, ...other } = value;
                this.$set(this.tableData, value.$index, other);
                resolve();
              });
            };
          }
        }
        submitAPI(this.valueForm, { type: this.modalType })
          .then(() => {
            if (this.$listeners['submit-success']) {
              this.$emit('submit-success');
            } else {
              if (this.tips) {
                this.$message.success('保存成功');
              }
            }
            this.closeDialog();
            this.search();
          })
          .finally(() => {
            this.submitting = false;
          });
      }
    },
    // 打开新增
    openNew() {
      this.openDialog('new', '新增');
    },
    // 打开编辑
    openEdit(row) {
      this.dialogLoading = true;
      this.openDialog('edit', '编辑');
      const getRow = () =>
        new Promise(resolve => {
          resolve(cloneDeep(row));
        });
      const getAPI = this.apiGet || getRow;
      getAPI(cloneDeep(row))
        .then(result => {
          if (result) {
            this.$emit('update:value-form', result);
          }
        })
        .finally(() => {
          this.dialogLoading = false;
        });
    },
    // 打开详情
    openDetail(row) {
      this.dialogLoading = true;
      this.openDialog('detail', '详情');
      const getRow = () =>
        new Promise(resolve => {
          resolve(cloneDeep(row));
        });
      const getAPI = this.apiDetail || this.apiGet || getRow;
      getAPI(cloneDeep(row))
        .then(result => {
          if (result) {
            this.detail = result;
            this.$emit('update:value-detail', result);
          }
        })
        .finally(() => {
          this.dialogLoading = false;
        });
    },
    // 打开弹出框
    openDialog(type, title, config) {
      this.modalRender = true;
      this.modalType = type;
      this.modalTitle = title;
      this.modalProps = config || {};
      this.visible = true;
      this.$emit('dialog-change', type);
    },
    // 关闭弹出框
    closeDialog() {
      this.visible = false;
    },
    // 弹出框显示状态更新
    onVisibleUpdate(visible) {
      this.visible = visible;
    },
    // 弹出框关闭
    onDialogClose() {
      this.modalType = 'none';
      this.$emit('dialog-change', 'none');
    },
    // 弹出框关闭动画结束
    onDialogClosed() {
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
      this.modalRender = false;
      this.modalProps = {};
      this.$emit('update:value-form', this.cloneDeep(this.originProps).valueForm);
      this.$emit('update:value-detail', this.cloneDeep(this.originProps).valueDetail);
    },
    // 表格选中状态
    onTableSelectionChange(selection, type) {
      this.selection = selection;
    },
    // 分页-每页个数
    onSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.$nextTick(this.search);
    },
    // 分页-当前页数
    onCurrentChange(val) {
      this.currentPage = val;
      this.$nextTick(this.search);
    },
    // 删除数据
    onDelete(selection) {
      const loading = this.$loading({
        lock: true,
        text: '处理中',
        spinner: 'el-icon-loading',
        customClass: 'eagle-loading-toast',
        background: 'rgba(0, 0, 0, 0)',
      });
      let deleteAPI = this.apiDelete || this.emptyPromise;
      if (this.datagrid) {
        deleteAPI = () => {
          return new Promise(resolve => {
            this.tableData = this.datagridData
              .filter(row => {
                return !selection.map(i => i.$index).includes(row.$index);
              })
              .map(({ $index, ...other }) => {
                return other;
              });
            resolve();
          });
        };
      }
      deleteAPI(selection)
        .then(() => {
          this.search();
          if (this.$listeners['delete-success']) {
            this.$emit('delete-success');
          } else {
            if (this.tips) {
              this.$message.success('删除成功');
            }
          }
        })
        .finally(() => {
          loading.close();
        });
    },
    // 批量删除
    onDeleteMultiple(selection) {
      this.$confirm(`是否删除这 [${selection.length}] 项?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.onDelete(selection);
        })
        .catch(() => {});
    },
  },
};
</script>