normal.vue 2.4 KB
<template>
  <el-table :data="tableData" :size="tableSize" v-bind="bindProps" v-on="$listeners">
    <slot name="left"></slot>
    <template v-for="(item, index) in columns">
      <el-table-column v-bind="item" :key="index">
        <slot :name="`header-${item.prop}`" slot="header"></slot>
        <template v-if="$scopedSlots[`cell-${item.prop}`]" #default="{ row, column, $index }">
          <slot :name="`cell-${item.prop}`" :value="get(row, item.prop)" :row="row" :column="column" :index="$index"></slot>
        </template>
        <template v-else-if="item.render && typeof item.render === 'function'" #default="{ row, column, $index }">
          <cell-render :item="item" :value="get(row, item.prop)" :row="row" :column="column" :index="$index"></cell-render>
        </template>
      </el-table-column>
    </template>
    <slot></slot>
    <slot name="append"></slot>
  </el-table>
</template>

<script>
import tableProps from './props';
import { get } from '../utils';

export default {
  name: 'TableNormal',
  components: {
    CellRender: {
      functional: true,
      render(h, context) {
        const props = context.props;
        const item = props.item || {};
        const content = item.render(props.value, props.row, h, props.index);
        return typeof content === 'string' ? h('span', {}, [content]) : content;
      },
    },
  },
  inject: {
    elForm: {
      default: '',
    },
    elFormItem: {
      default: '',
    },
  },
  props: {
    value: {
      type: Array,
      default() {
        return [];
      },
    },
    columns: {
      type: Array,
      default() {
        return [];
      },
    },
    ...tableProps,
  },
  data() {
    return {
      tableData: this.value.length > 0 ? this.value : this.data,
    };
  },
  watch: {
    value(val) {
      this.tableData = val || [];
    },
    data(val) {
      this.tableData = val || [];
    },
  },
  computed: {
    _elFormItemSize() {
      return (this.elFormItem || {}).elFormItemSize;
    },
    tableSize() {
      return this.size || this._elFormItemSize || (this.elForm || {}).size || (this.$ELEMENT || {}).size;
    },
    bindProps() {
      const tablePropsKeys = Object.keys(tableProps);
      let props = {};
      Object.keys(this._props).forEach(key => {
        if (tablePropsKeys.includes(key)) {
          props[key] = this._props[key];
        }
      });
      return props;
    },
  },
  methods: {
    get,
  },
};
</script>