dcy-microservices-platform-4、前端table-page组件封装和axios封装

卢黎昕
2023-12-01

代码

axios封装

创建axios.js

import axios from 'axios'
import store from '@/store'
import {Message, Notice} from 'iview'

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
  }

  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {}
    }
    return config
  }

  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 权限信息
      if (store.getters.token) {
        config.headers['Authorization'] = store.getters.token
      }
      return config
    }, error => {
      console.log(error) // for debug
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      // 数据源格式
      // code data msg success
      const data = res.data;
      if (data.code !== 200) {
        Notice.error({title: 'error', desc: error, duration: 5 * 1000});
      } else {
        return data
      }
    }, error => {
      switch (error.response.status) {
        case 403:
          Notice.error({title: 'error', desc: '拒绝访问,请联系管理员', duration: 5 * 1000});
          break;
        default:
          Notice.error({title: 'error', desc: error, duration: 5 * 1000});
      }
      return Promise.reject(error)
    })
  }

  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}

export default HttpRequest

创建api.request.js文件

import HttpRequest from '@/libs/axios'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : '/api';

const axios = new HttpRequest(baseUrl)
export default axios

notice封装

import {Notice} from 'iview'

const ADD_SUCCESS_NOTICE = '添加成功';
const UPDATE_SUCCESS_NOTICE = '修改成功';
const DELETE_SUCCESS_NOTICE = '删除成功';
const SAVE_SUCCESS_NOTICE = '保存成功';
const ADD_ERROR_NOTICE = '添加失败';
const UPDATE_ERROR_NOTICE = '修改失败';
const DELETE_ERROR_NOTICE = '删除失败';
const SAVE_ERROR_NOTICE = '保存失败';
const NOTICE_DURATION = 3

/**
 * 获取通知配置
 * @param title
 * @param desc
 * @param duration
 * @returns {{duration: *, title: *, desc: *}}
 */
export const noticeConfig = (title, desc = null, duration = 3) => {
  return {title: title, desc: desc, duration: duration}
}

/**
 * 成功通知
 * @param type
 * @param desc
 */
export const noticeSuccess = (type, desc = null) => {
  switch (type) {
    case 'add':
      Notice.success({title: ADD_SUCCESS_NOTICE, desc: desc, duration: NOTICE_DURATION});
      break;
    case 'upd':
      Notice.success({title: UPDATE_SUCCESS_NOTICE, desc: desc, duration: NOTICE_DURATION});
      break;
    case 'del':
      Notice.success({title: DELETE_SUCCESS_NOTICE, desc: desc, duration: NOTICE_DURATION});
      break;
    default:
      Notice.success({title: SAVE_SUCCESS_NOTICE, desc: desc, duration: NOTICE_DURATION});
  }
}

/**
 * 失败通知
 * @param type
 * @param desc
 */
export const noticeError = (type, desc = null) => {
  switch (type) {
    case 'add':
      Notice.error({title: ADD_ERROR_NOTICE, desc: desc, duration: NOTICE_DURATION});
      break;
    case 'upd':
      Notice.error({title: UPDATE_ERROR_NOTICE, desc: desc, duration: NOTICE_DURATION});
      break;
    case 'del':
      Notice.error({title: DELETE_ERROR_NOTICE, desc: desc, duration: NOTICE_DURATION});
      break;
    default:
      Notice.error({title: SAVE_ERROR_NOTICE, desc: desc, duration: NOTICE_DURATION});
  }
}

表格分页封装

<template>
  <div>
    <Table
      ref="tableMain"
      :columns="columns"
      :stripe="stripe"
      :border="border"
      :show-header="showHeader"
      :width="width"
      :height="height"
      :max-height="maxHeight"
      :loading="loading"
      :size="size"
      :data="data"
      @on-sort-change="tableSort"
      @on-selection-change="tableSelect">
      <!-- 自定义列 -->
      <template v-for="col in columnsTable" slot-scope="{row,column,index}" :slot="col.slot">
        <slot :row="row" :index="index" :column="column" :name="col.slot"></slot>
      </template>
      <slot name="header" slot="header"></slot>
      <slot name="footer" slot="footer"></slot>
      <slot name="loading" slot="loading"></slot>
    </Table>
    <div style="margin: 10px;overflow: hidden">
      <div style="float: right" v-if="pageIng">
        <Page
          ref="selection"
          :current="current"
          :total="total"
          :page-size="pageSize"
          :page-size-opts="pageSizeOpts"
          :size="pageTypeSize"
          :simple="pageSimple"
          :show-total="showTotal"
          :show-elevator="showElevator"
          :show-sizer="showSizer"
          @on-change="handlePage"
          @on-page-size-change="handlePageSize"/>
      </div>
    </div>
  </div>
</template>

<script>

import { getModulesTables } from '@/api/common'

export default {
  name: 'dcy-table',
  data () {
    return {
      sidePagination: true, // 服务端模式
      // 表格配置相关
      loading: false, // 表格是否加载中
      // 分页相关
      sortTable: this.sort, // 排序字段
      orderTable: this.order, // 排序类型
      // checkBox:true,// 是否显示checkBox
      current: 1, // 当前页面
      pageSizeTable: this.pageSize, // 每页显示多少条
      total: 0, // 一共多少页
      // pageSizeOpts: [10, 20, 30, 100], // 每页条数选择框
      initPage: 1, // 初始页面
      // 分页相关
      // pageIng: true,
      // showTotal: true,
      // showSizer: true,
      // showElevator: true,
      // 数据相关
      data: [], // 返回数据
      ids: []
    }
  },
  computed: {
    columnsTable () {
      // 自定义列
      return this.columns.filter(e => e.hasOwnProperty('slot'))
    }
  },
  props: {
    // 表格配置
    /* data: {
                type: Array
            }, */
    columns: {
      // 列头
      type: Array,
      require: true
    },
    stripe: {
      // 是否显示间隔斑马纹
      type: Boolean,
      default: false
    },
    border: {
      // 是否显示纵向边框
      type: Boolean,
      default: true
    },
    showHeader: {
      // 是否显示表头
      type: Boolean,
      default: true
    },
    width: {
      // 表格宽度,单位 px
      type: [Number, String]
    },
    height: {
      // 表格高度,单位 px,设置后,如果表格内容大于此值,会固定表头
      type: [Number, String]
    },
    maxHeight: {
      // 表格最大高度,单位 px,设置后,如果表格内容大于此值,会固定表头
      type: [Number, String]
    },
    /* loading: {
                // 表格是否加载中
                type: Boolean,
                default: false
            }, */
    size: {
      // 表格尺寸,可选值为 large、small、default 或者不填
      type: String,
      default: 'default'
    },
    // 分页 相关
    pageIng: {
      // 是否分页
      type: Boolean,
      default: true
    },
    pageSize: {
      // 每页条数
      type: Number,
      default: 10
    },
    pageSizeOpts: {
      // 每页条数切换的配置
      type: Array,
      default: function () {
        return [10, 20, 30, 100]
      }
    },
    pageTypeSize: {
      // 可选值为small(迷你版)或不填(默认)
      type: String
    },
    pageSimple: {
      // 简洁版
      type: Boolean,
      default: false
    },
    showTotal: {
      // 显示总数
      type: Boolean,
      default: true
    },
    showElevator: {
      // 显示电梯,可以快速切换到某一页
      type: Boolean,
      default: true
    },
    showSizer: {
      // 显示分页,用来改变page-size
      type: Boolean,
      default: true
    },
    // 查询参数配置
    queryParams: {// 查询参数
      type: Object
    },
    uniqueId: {
      type: String, // 每一行的唯一标识
      default: 'id'
    },
    sort: {
      // 排序字段
      type: String,
      default: null
    },
    order: {
      // 排序类型
      type: String,
      default: null
    },
    url: {// url 必须的
      type: String,
      require: true
    },
    checkBox: {
      // 是否显示checkBox
      type: Boolean,
      default: true
    }
  },
  methods: {
    /**
             * page组件 => 页码改变的回调
             * @param value
             */
    handlePage (value) {
      if (this.checkBox) {
        this.$emit('table-select-val', [])
      }
      this.getData(value)
    },
    /**
             * page组件 => 切换每页条数时的回调
             * @param value
             */
    handlePageSize (value) {
      if (this.checkBox) {
        this.$emit('table-select-val', [])
      }
      this.pageSizeTable = value
      this.getData(this.initPage)
    },
    /**
             * table组件 => 排序时有效,当点击排序时触发
             * @param column
             */
    tableSort (column) {
      this.sortTable = column.key
      this.orderTable = column.order
      this.getData(this.current)
    },
    /**
             * table组件 => 在多选模式下有效,只要选中项发生变化时就会触发
             * @param selection
             */
    tableSelect (selection) {
      // 获取所有选中值
      this.ids = selection.map(val => val[this.uniqueId])
      // 往父组件传参数
      this.$emit('table-select-val', this.ids)
    },
    /**
             * 获取数据
             * @param pageNum
             */
    getData (pageNum) {
      // 定义分页对象
      let pageObj = {
        current: pageNum,
        size: this.pageSizeTable,
        sort: this.sortTable,
        order: this.orderTable
      }
      if (this.queryParams != null) {
        Object.assign(pageObj, this.queryParams)
      }
      this.loading = true
      getModulesTables(this.url, 'get', pageObj).then((response) => {
        // 是否包含这个key
        if (response.data.hasOwnProperty('records')) {
          this.current = pageNum
          this.data = response.data.records
          this.total = response.data.total
        } else {
          this.data = response.data
          // 分页相关
          this.pageIng = false
        }
        this.loading = false
      })
    },
    refresh () {
      // 刷新
      this.getData(this.initPage)
    },
    selectAll (bool) {
      this.$refs.tableMain.selectAll(bool)
    }
  },
  created () {
    if (this.checkBox) {
      this.columns.unshift({
        type: 'selection',
        width: 60,
        align: 'center'
      })
    }
  },
  mounted () {
    this.getData(this.initPage)
  }
}
</script>

<style scoped>

</style>

使用方式

<!-- 表格 -->
    <dcy-table
      ref="dcyTable"
      unique-id="userId"
      size="large"
      :query-params="queryParams"
      :url="url"
      @table-select-val="selectVal"
      :columns="columns">
      <template slot-scope="{ row, index }" slot="sex">
        <Tag color="blue" v-if="row.sex === '0'">男</Tag>
        <Tag color="green" v-if="row.sex === '1'">女</Tag>
      </template>
      <template slot-scope="{ row, index }" slot="userStatus">
        <Tag color="success" v-if="row.userStatus === '0'">正常</Tag>
        <Tag color="error" v-if="row.userStatus === '1'">禁用</Tag>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <a @click="update(row)">修改</a>
        <Divider type="vertical"/>
        <a @click="remove(row)">删除</a>
        <Divider type="vertical"/>
        <a @click="resetPassword(row)">重置密码</a>
        <Divider type="vertical"/>
        <a @click="authRole(row)">授权角色</a>
        <Divider type="vertical"/>
        <a @click="authGroup(row)">授权用户组</a>
      </template>
    </dcy-table>


data----------
url: '/admin-service/user/page',
columns: [
    {title: '用户名', key: 'username', align: 'center', sortable: true},
    {title: '昵称', key: 'nickName', align: 'center'},
    {title: '邮箱', key: 'email', align: 'center'},
    {title: '手机号码', key: 'phoneNumber', align: 'center'},
    {title: '性别', slot: 'sex', align: 'center'},
    {title: '状态', slot: 'userStatus', align: 'center'},
    {title: '操作', slot: 'action', align: 'center', width: 400}
],
queryParams: {},

刷新表格

/**
 * 刷新
 */
refresh() {
    // 清空选中状态
    this.$refs.dcyTable.selectAll(false);
    this.$refs.dcyTable.refresh()
},
 类似资料: