el-table 如何根据接口内的某个字段来加载数据?

现在是想根据后端返回的接口里面某个字段,来加载包含该字段的所有数据在表格展示,比如我根据json里面状态字段来获取数据,状态包含启用 active 和 禁用 FREEZE

我只想要包含启用 active 的所有数据,怎么实现?
个人封装的table

<template>
  <div class="app-table">
    <slot name="header" class="app-table-header"></slot>
    <el-table
      ref="customTable"
      :data="tableData"
      class="app-table-content"
      stripe
      :tooltip-effect="tooltipEffect"
      :highlight-current-row="highlightCurrentRow"
      @selection-change="selectionChange"
      @select="select"
      @select-all="selectAll"
      @row-click="selectRowClick"
      @expand-change="expandChange"
      :default-expand-all="expandAll"
      v-bind="expandObj"
      @sort-change="sortChange"
      :current-row-key="currentRowKey"
      :size="tableSize"
      v-loading="loading"
    >
      <div slot="empty" class="no-data" v-show="isEmptyData">
        <div class="empty-icon"></div>
        <div class="empty-text">暂无数据</div>
      </div>
      <el-table-column v-if="columnTypes.indexOf('expand') !== -1" type="expand">
        <template v-slot:default="scope">
          <slot name="expandSlot" :row="scope.row" :$index="scope.$index" />
        </template>
      </el-table-column>
      <el-table-column
        v-if="columnTypes.indexOf('selection') !== -1"
        width="55px"
        type="selection"
        :reserve-selection="true"
      >
      </el-table-column>
      <el-table-column
        v-if="columnTypes.indexOf('index') !== -1"
        label="序号"
        width="100px"
        type="index"
      >
      </el-table-column>
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
        :min-width="column.minWidth"
        :show-overflow-tooltip="column.showOverflowTooltip"
        :fixed="column.fixed"
        :sortable="column.sortable"
        :align="column.align"
      >
        <!--自定义列头-->
        <template v-slot:header v-if="column.slotHeader">
          <slot :name="column.slotHeader" :column="column"></slot>
        </template>
        <template v-slot:default="scope">
          <!--自定义列内容-->
          <span v-if="column.slotName">
            <slot
              :name="column.slotName"
              :row="scope.row"
              :$index="scope.$index"
              :$count="tableData.length"
              :$pagination="pagination"
            />
          </span>
          <!--格式化内容-->
          <span v-else-if="column.formatter">{{ column.formatter(scope.row, column) }}</span>
          <span v-else>
            {{ initColValue(scope.row, column.prop) }}
          </span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="showPage && total > pagination.pageSizes[0]"
      :small="pagination.small"
      :total="total"
      :current-page="pagination.current"
      :page-sizes="pagination.pageSizes"
      :page-size="pagination.limit"
      class="app-table-pagination"
      :layout="pagination.layout"
      @current-change="pageChange"
      @size-change="pageSizeSelect"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  props: {
    // table columns
    columns: {
      type: Array,
      required: true,
    },
    // 额外表格列,selection/index/expand
    columnTypes: {
      type: Array,
      default: () => [],
    },
    // 获取table data 方法,需要返回promise
    service: {
      type: Function,
    },
    datas: {
      type: Array,
      default: () => [],
    },
    // 查询table参数处理
    beforeSearch: {
      type: Function,
      default: (params) => params,
    },
    // 查询table 结果处理
    afterSearch: {
      type: Function,
      default: (res) => res,
    },
    rowKey: {
      type: [String, Function],
    },
    expandAll: {
      type: Boolean,
      default: false,
    },
    expandRowKeys: {
      type: Array,
      default: () => [],
    },
    showPage: {
      type: Boolean,
      default: true,
    },
    // 分页默认配置
    pageOpt: {
      type: Object,
      default: () => ({}),
    },
    highlightCurrentRow: {
      type: Boolean,
      default: false,
    },
    currentRowKey: {
      type: [String, Number],
      default: '',
    },
    tooltipEffect: {
      type: String,
      default: 'dark',
    },
    rowClick: {
      type: Function,
      default: () => {},
    },
    tableSize: {
      type: String,
      default: 'medium',
    },
    selectRow: {
      //父组件传递过来的要选中的行的id
      type: Array,
      default: null,
    },
    // 是不是在created阶段执行搜索
    immediateSearch: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      isEmptyData: false,
      loading: false,
      tableData: [],
      selectioned: '',
      total: 0,
      rowKeys: this.expandRowKeys ? [...this.expandRowKeys] : [],
      pagination: {
        small: this.pageOpt.small || false,
        current: 1,
        limit: this.pageOpt.limit || 10,
        pageSizes: this.pageOpt.pageSizes || [10, 20, 50, 100],
        layout: this.pageOpt.layout || 'total, sizes, prev, pager, next, jumper',
      },
    };
  },
  computed: {
    expandObj() {
      if (this.rowKey) {
        return {
          'row-key': this.rowKey,
          'expand-row-keys': this.rowKeys,
        };
      }
      return {};
    },
    isBackEnd() {
      return !!this.service;
    },
  },
  watch: {
    service() {
      this.search();
    },
    expandRowKeys: {
      handler(val) {
        this.rowKeys = val;
      },
    },
    datas: {
      handler() {
        this.pagination.limit = 10;
        this.pagination.current = 1;
        this.getTableDatas();
      },
      deep: true,
    },
  },
  created() {
    if (this.isBackEnd && this.immediateSearch) {
      this.search();
    }
  },
  methods: {
    sortChange({ column, prop, order }) {
      this.$emit('sortChange', { column, prop, order });
    },
    pageChange(current) {
      this.pagination.current = current;
      this.$emit('pageChange', current);
      this.getTableDatas();
    },
    pageSizeSelect(size) {
      this.pagination.limit = size;
      this.$emit('pageSizeChange', size);

      this.search();
    },
    // 重置当前页 重新检索
    search() {
      this.pagination.current = 1;
      this.getTableDatas();
    },
    // 根据当前条件检索
    getTableDatas() {
      // 组装参数
      const { limit, current } = this.pagination;
      if (!this.isBackEnd) {
        this.tableData = this.datas.slice((current - 1) * limit, limit * current);
        this.total = this.datas.length;
        return;
      }
      const data = {
        pageSize: limit,
        pageNum: current, // 当前页page数
      };
      // this.tableData = [];
      this.loading = true;
      // 查询前处理参数
      const params = this.beforeSearch(data);
      this.service(params)
        .then((res) => {
          this.loading = false;
          // 查询后处理结果
          const { total = 0, list } = this.afterSearch(res);
          this.tableData = list;
          this.total = total;
          // 重新设置expandRowKeys 不然不会默认展开
          // eslint-disable-next-line no-debugger
          if (this.rowKey && this.rowKeys) {
            this.rowKeys = this.rowKeys.slice(0);
          }
          if (total === 0) {
            this.isEmptyData = true;
          } else {
            this.isEmptyData = false;
          }
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
          // this.$message.error(err.errorMsg || '获取列表数据出错!');
        });
    },
    initColValue(row, prop) {
      let result = row;
      if (prop && prop.indexOf('.') !== -1) {
        prop.split('.').forEach((vv) => {
          result = result[vv];
        });
      } else {
        result = result[prop];
      }
      return result;
    },
    selectionChange(selection) {
      this.$emit('selection-change', selection);
    },
    selectRowClick(rows) {
      this.$emit('row-click', rows);
    },
    toggleRowSelection(row, selected) {
      this.$refs.customTable.toggleRowSelection(row, selected);
    },
    select(row) {
      this.$emit('select', row);
    },
    selectAll(row) {
      this.$emit('select-all', row);
    },
    expandChange(row, expandedRows) {
      this.$emit(
        'expand-change',
        row,
        expandedRows.map((item) => item[this.rowKey])
      );
    },
    setCurrentRow(row) {
      this.$refs.customTable.setCurrentRow(row);
    },
    clearSelections() {
      this.$refs.customTable.clearSelection();
    },
  },
};
</script>

下面是使用二次封装了el-table

<app-table
            ref="tableUser"
            :service="tableUserService"
            :columns="columnsUser"
            :columnTypes="columnTypes"
            :beforeSearch="handleParamsUser"
            :tooltip-effect="tooltipEffect"
            rowKey="id"
            @select="tableRowClick"
            @select-all="tableRowClick"
            :pageOpt="{ layout: 'prev, pager, next', limit: 5 }"
          >
            <template v-slot:status="{ row }">
              <span :class="[row.status == 'ACTIVE' ? 'normal-style' : 'lock-style']">
                {{ row.status === 'ACTIVE' ? '启用' : '禁用' }}
              </span>
            </template>
          </app-table>

:service="tableUserService"
实现方法

this.tableUserService = getUserList

getUserList是封装的接口方法
数据
image.png

阅读 1.9k
1 个回答

看到你封装了 app-table 明白了。组件已经暴露出了 afterSearch 方法,使用这个即可。

<app-table
    // ...
    :beforeSearch="handleParamsUser"

    :afterSearch="handleFormatRes"
    // ...
  >
    <template v-slot:status="{ row }">
      <span :class="[row.status == 'ACTIVE' ? 'normal-style' : 'lock-style']">
        {{ row.status === 'ACTIVE' ? '启用' : '禁用' }}
      </span>
    </template>
  </app-table>

<script>
//...
methods: {
    handleFormatRes: res => ({
        ...res,
        list: res.list.filter(item => item.status === 'active')
    })
}
</script>

原回答:

看上面你的疑问,直接过滤下就OK了呀

getUserList().then((res) => {
    this.tableUserService = res.filter(item => item.status === 'active')
});

// 或者
this.tableUserService = await getUserList().filter(item => item.status === 'active')
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题