dcy-microservices-platform-4、前端table-page組件封裝和axios封裝

代碼

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()
},
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章