vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > element表格和表单的封装

关于element中表格和表单的封装方式

作者:仙女不讲李

这篇文章主要介绍了关于element中表格和表单的封装方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

pc端基础的表格组件的封装

list.vue

<!--region 封装的分页 table-->
<template>
  <div class="table">
    <!-- <el-card shadow="always" class="card-table"> -->
    <el-table
      id="iTable"
      ref="mutipleTable"
      v-loading.iTable="options.loading"
      highlight-current-row
      :data="list"
      :stripe="options.stripe"
      :row-key="rowKey"
      :row-class-name="rowClassName"
      :header-cell-style="{
        'text-align': 'center',
        background: '#051b54',
        color: '#EBEBEB',
        'font-weight': '400',
      }"
      @row-click="rowClick"
      @selection-change="handleSelectionChange"
    >
      >
      <!--region 选择框-->
      <el-table-column v-if="options.mutiSelect" type="selection" :resizable="false" />
      <!--endregion-->
      <!--region 数据列-->
      <template v-for="(column, index) in columns">
        <el-table-column
          :key="column.label"
          :resizable="false"
          :prop="column.prop"
          :label="column.label"
          :align="column.align ? column.align : 'center'"
          :width="column.width"
          :show-overflow-tooltip="column.showOverflowTooltip"
        >
          <template slot-scope="scope">
            <template v-if="!column.render">
              {{ column.render }}
              <template v-if="column.formatter">
                <span v-html="column.formatter(scope.row, column)" />
              </template>
              <template v-else>
                <span v-if="scope.row[column.prop] && column.prop !== 'icon'">{{
                  scope.row[column.prop]
                }}</span>
                <span v-else-if="scope.row[column.prop] === 0">{{ scope.row[column.prop] }}</span>
                <svg-icon
                  v-else-if="scope.row[column.prop] && column.prop === 'icon'"
                  :icon-class="scope.row[column.prop]"
                  class="header-svg"
                />
                <span v-else>-</span>
              </template>
            </template>
            <template v-else>
              <expand-dom
                :column="column"
                :row="scope.row"
                :render="column.render"
                :index="index"
              />
            </template>
          </template>
        </el-table-column>
      </template>
      <!--endregion-->
      <!--region 按钮操作组-->
      <el-table-column
        v-if="operates.list.length > 0"
        ref="fixedColumn"
        :resizable="false"
        label="操作"
        align="center"
        :width="operates.width"
        :fixed="operates.fixed"
      >
        <template slot-scope="scope">
          <div class="operate-group">
            <template v-for="btn in operates.list">
              <div v-if="!btn.show || btn.show(scope.row)" :key="btn.label" class="item">
                <!-- v-if="!btn.isAuth || btn.isAuth()" -->
                <el-button
                  v-if="!btn.isAuth || btn.isAuth()"
                  round
                  :type="btn.type"
                  size="mini"
                  :icon="btn.icon"
                  :disabled="btn.disabled && btn.disabled(scope.row)"
                  :plain="btn.plain"
                  @click.native.prevent="btn.method(scope.row)"
                >
                  {{ btn.label }}
                </el-button>
              </div>
            </template>
          </div>
        </template>
      </el-table-column>
      <!--endregion-->
    </el-table>
    <!-- </el-card> -->
    <!--region 分页-->
    <el-pagination
      v-show="showPagination"
      v-if="pagination"
      :page-size="tableCurrentPagination.pageSize"
      :page-sizes="tableCurrentPagination.pageArray"
      :current-page="tableCurrentPagination.page"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleIndexChange"
    />
    <!--endregion-->
  </div>
</template>
<!--endregion-->
<script>
const _pageArray = [10, 20, 50] // 每页展示条数的控制集合
export default {
  name: 'Table',
  components: {
    expandDom: {
      functional: true,
      props: {
        row: Object,
        render: Function,
        index: Number,
        column: {
          type: Object,
          default: null,
        },
      },
      render: (h, ctx) => {
        const params = {
          row: ctx.props.row,
          index: ctx.props.index,
        }
        if (ctx.props.column) params.column = ctx.props.column
        return ctx.props.render(h, params)
      },
    },
  },
  props: {
    list: {
      type: Array,
      default: () => [], // prop:表头绑定的地段,label:表头名称,align:每列数据展示形式(left, center, right),width:列宽
    }, // 数据列表
    columns: {
      type: Array,
      default: () => [], // 需要展示的列 === prop:列数据对应的属性,label:列名,align:对齐方式,width:列宽
    },
    rowKey: {
      type: String,
      default: '',
    },
    rowClassName: {
      type: Function,
      default: () => {
        return Function
      },
    },
    operates: {
      type: Object,
      default: () => {}, // width:按钮列宽,fixed:是否固定(left,right),按钮集合 === label: 文本,type :类型(primary / success / warning / danger / info / text),show:是否显示,icon:按钮图标,plain:是否朴素按钮,disabled:是否禁用,method:回调方法
    },
    options: {
      type: Object,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: {
        stripe: true, // 是否为斑马纹 table
        loading: true, // 是否添加表格loading加载动画
        highlightCurrentRow: true, // 是否支持当前行高亮显示
        mutiSelect: false, // 是否支持列表项选中功能
      },
    },
    showPagination: {
      type: Boolean,
      default: true,
    },
    // pagination: {
    //   type: Object,
    //   default: {
    //     page: 1,
    //     pageSize: 10
    //   }
    // },
    total: {
      type: Number,
      default: 0,
    },
    // 总数
    otherHeight: {
      type: Number,
      default: 160,
    }, // 计算表格的高度
  },
  data() {
    return {
      tableCurrentPagination: {},
      multipleSelection: [], // 多行选中
    }
  },
  mounted() {
    if (this.pagination && !this.pagination.pageSizes) {
      this.tableCurrentPagination.pageArray = _pageArray // 每页展示条数控制
    }
    this.tableCurrentPagination = this.pagination || {
      pageSize: this.total,
      page: 1,
    } // 判断是否需要分页
  },
  methods: {
    rowClick(row) {
      this.$emit('rowClick', row)
    },
    // 切换每页显示的数量
    handleSizeChange(size) {
      if (this.pagination) {
        this.tableCurrentPagination = {
          page: 1,
          pageSize: size,
        }
        this.$emit('handleSizeChange', this.tableCurrentPagination)
        // 跳转页面后回页面顶部
        this.$nextTick(() => {
          this.$refs.mutipleTable.bodyWrapper.scrollTop = 0
          document.body.scrollTop = document.documentElement.scrollTop = 0
        })
      }
    },
    // 切换页码
    handleIndexChange(currnet) {
      if (this.pagination) {
        this.tableCurrentPagination.page = currnet
        this.$emit('handleIndexChange', this.tableCurrentPagination)
        // 跳转页面后回页面顶部
        this.$nextTick(() => {
          this.$refs.mutipleTable.bodyWrapper.scrollTop = 0
          document.body.scrollTop = document.documentElement.scrollTop = 0
        })
      }
    },
    // 多行选中
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.$emit('handleSelectionChange', val)
    },
    // 显示 筛选弹窗
    showfilterDataDialog() {
      this.$emit('handleFilter')
    },
    // 显示 表格操作弹窗
    showActionTableDialog() {
      this.$emit('handelAction')
    },
  },
}
</script>
<style lang="scss" scoped>
.table {
  /deep/tr {
    background-color: transparent !important;
    border-bottom: none !important;
  }
  /deep/ td,
  th.is-leaf {
    border-bottom: none !important;
  }
  /deep/th,
  tr {
    background-color: transparent;
    border-bottom: none !important;
  }
  /deep/ .current-row td {
    background-color: #051b54 !important;
  }
  /deep/ .hover-row td {
    background-color: #051b54 !important;
  }
  /* 鼠标移入表格高亮yanse */
  /deep/ tbody tr:hover > td {
    background-color: #051b54 !important;
  }
  /deep/ tbody tr:hover {
    background-color: #051b54 !important;
  }
  /deep/ .el-table__fixed-right::before,
  .el-table__fixed::before {
    background-color: transparent !important;
  }
}
.el-table--border::after,
.el-table--group::after,
.el-table::before {
  //去除表格底部白线
  background-color: transparent !important;
}
.el-pagination {
  text-align: right;
  /deep/ .el-pagination__total,
  /deep/ .el-pagination__jump {
    color: #959abb !important;
  }
  /deep/ .el-input__inner {
    background-color: #0d102a !important;
    border-color: #2a3259;
    color: #959abb;
  }
  /deep/ .btn-prev,
  /deep/ .el-pager .number,
  /deep/ .btn-next {
    background-color: #0d102a !important;
  }
  /deep/ .el-pager .number {
    color: #959abb;
  }
  /deep/ .el-pager .number:hover {
    color: #fff;
  }
  /deep/.el-pager .active {
    color: #fff;
  }
  /deep/ .btn-next:hover,
  /deep/ .btn-prev:hover {
    color: #409eff;
  }
  /deep/ .btn-next,
  /deep/ .btn-prev {
    color: #fff;
  }
  /deep/ button:disabled {
    color: #959abb;
  }
  /deep/ .el-icon {
    background-color: transparent;
    color: #959abb;
  }
  /deep/ .el-icon-d-arrow-right {
    color: #fff;
  }
  /deep/ .el-icon:hover {
    color: #fff;
  }
  /deep/ .el-icon-arrow-up:hover {
    color: #fff;
  }
}
</style>

pc端基础的表单组件的封装

elForm.vue

<!--
 * @Descriptin: 修改了一些内容
 * @Version: 1.0
 * @Autor: wxy
 * @Date: 2021-06-29 09:20:09
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-02 15:05:15
-->
<template>
  <el-form
    ref="form"
    :inline="inline"
    :label-width="labelWidth"
    class="datafill-elform"
    :model="baseData"
    :rules="rules"
    @keyup.enter.native="dataFormSubmit(baseData)"
  >
    <el-row>
      <el-col>
        <el-form-item
          v-for="item in baseForm"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :required="item.required"
        >
          <!-- 输入框 -->
          <el-input
            v-if="item.type === 'Input'"
            v-model="baseData[item.prop]"
            class="input"
            :readonly="item.readonly ? item.readonly : false"
            :type="item.inputType ? item.inputType : 'text'"
            :rows="6"
            :maxlength="item.maxlength ? item.maxlength : 256"
            :disabled="item.disabled"
            :clearable="item.clearable || true"
            :filterable="item.filterable || false"
            :placeholder="item.placeholder"
          />
          <span v-if="item.type === 'Input'" class="itemunit">{{ item.unit }}</span>
          <!-- 输入框 -->
          <el-input-number
            v-if="item.type === 'InputNumber'"
            v-model="baseData[item.prop]"
            controls-position="right"
            class="input"
            :readonly="item.readonly ? item.readonly : false"
            :type="item.inputType ? item.inputType : 'text'"
            :min="0"
            :precision="item.precision || 2"
            :disabled="item.disabled"
            :clearable="item.clearable || true"
            :placeholder="item.placeholder"
          />
          <span v-if="item.type === 'InputNumber'" class="itemunit">{{ item.unit }}</span>
          <!-- 下拉框 -->
          <el-select
            v-if="item.type === 'Select'"
            v-model="baseData[item.prop]"
            :multiple="item.multiple ? item.multiple : false"
            :collapse-tags="item.collapseTags ? item.collapseTags : false"
            :placeholder="item.placeholder"
            :clearable="item.clearable || true"
            :disabled="item.disabled"
            :popper-append-to-body="false"
            popper-class="select-popper"
            :filterable="item.filterable || false"
            @change="item.change ? item.change(baseData[item.prop]) : changeHandle"
          >
            <el-option
              v-for="op in item.options"
              :key="op.value"
              :label="op.label"
              :value="op.value"
              :disabled="op.disabled"
            />
          </el-select>
          <!-- 单选 -->
          <el-radio-group v-if="item.type === 'Radio'" v-model="baseData[item.prop]">
            <el-radio v-for="ra in item.radios" :key="ra.value" :label="ra.value">{{
              ra.label
            }}</el-radio>
          </el-radio-group>
          <!-- 复选框 -->
          <el-checkbox-group v-if="item.type === 'Checkbox'" v-model="baseData[item.prop]">
            <el-checkbox v-for="ch in item.checkboxs" :key="ch.value" :label="ch.value">{{
              ch.label
            }}</el-checkbox>
          </el-checkbox-group>
          <!-- 日期 -->
          <el-date-picker
            v-if="item.type === 'Date'"
            v-model="baseData[item.prop]"
            :picker-options="item.pickerOptions"
            :clearable="item.clearable || true"
            :type="item.dateType ? item.dateType : 'date'"
            :placeholder="item.placeholder"
            range-separator="至"
            :start-placeholder="item.startPlaceholder ? item.startPlaceholder : '开始时间'"
            :end-placeholder="item.endPlaceholder ? item.endPlaceholder : '结束时间'"
            :format="item.format ? item.format : 'yyyy-MM-dd'"
            :value-format="item.format ? item.format : 'yyyy-MM-dd'"
          />
          <!-- 月份 -->
          <el-date-picker
            v-if="item.type === 'Month'"
            v-model="baseData[item.prop]"
            type="month"
            :placeholder="item.placeholder"
            format="yyyy-MM"
            value-format="yyyy-MM"
          />
          <!-- 年份 -->
          <el-date-picker
            v-if="item.type === 'Year'"
            v-model="baseData[item.prop]"
            type="year"
            :placeholder="item.placeholder"
            format="yyyy"
            value-format="yyyy"
          />
          <!-- 文件上传 -->
          <import-picture
            v-if="item.type === 'Import'"
            ref="importPic"
            :picture.sync="baseData[item.prop]"
          />
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item v-for="item in searchHandle" :key="item.label">
          <el-button
            v-if="!item.show ? item.show : true"
            :class="item.class"
            :round="item.round"
            :type="item.type"
            size="small"
            @click.native.prevent="item.handle()"
          >
            {{ item.label }}
          </el-button>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
// import ImportPicture from '@/components/ImportPicture'
export default {
  // components: {
  //   ImportPicture
  // },
  props: {
    inline: {
      type: Boolean,
      default: false,
    },
    labelWidth: {
      type: String,
      default: '160px',
    },
    baseForm: {
      type: Array,
      default: () => [],
    },
    baseData: {
      type: Object,
      default: () => {},
    },
    searchHandle: {
      type: Array,
      default: () => [],
    },
    rules: {
      type: Object,
      default: () => {},
    },
    // changeHandle: {
    //   type: Function,
    //   require: false,
    //   default: this.change()
    // }
  },
  mounted() {
    // console.log(this.baseData)
  },
  methods: {
    changeHandle() {
      // console.log('1234567')
    },
    dataFormSubmit(form) {
      this.$emit('dataFormSubmit', form)
    },
  },
}
</script>
<style lang="scss">
.el-form-item {
  margin-bottom: 0;
}
.el-input__inner {
  background-color: rgba(1, 15, 48, 0.3);
  border: 0.005051rem solid #093154;
  color: #959abb;
}
.searchButton {
  width: 60px;
  height: 32px;
  background: rgba(9, 12, 38, 0.3);
  border: 1px solid #25407c;
  border-radius: 17px;
  font-size: 14px;
  color: rgba(59, 210, 239, 1);
}
.el-button--primary {
  width: 72px;
  height: 32px;
  background: rgba(49, 99, 168, 0.3);
  border: 1px solid #25407c;
  border-radius: 2px;
}
</style>

表格的样式

table.scss

// base-list表格通用样式
.table {
  // height: 100%;
  background: transparent;
  .el-table__row {
    background-color: #0b2570 !important;
    color: #959abb;
    border: none;
  }
  /* 奇数行 */
  .el-table__row:nth-of-type(odd) > td {
    background-color: #0b2570;
  }
  /* 偶数行 */
  .el-table__row:nth-of-type(even) > td {
    background-color: #051b54 !important;
  }
  // 分页
  .el-pagination {
    float: right;
    margin: 10px;
  }
  // 操作列
  .operate-group {
    display: flex;
    flex-wrap: wrap;
    .item {
      display: block;
      // flex: 0 0 50%;
      margin: 0 5px;
    }
  }
  .el-table__empty-block {
    background-color: #161a3d;
    color: #fff;
  }
  .el-loading-mask {
    background: transparent;
  }
  .el-table__expand-icon {
    color: #959abb !important;
  }
}

表单的样式

element.scss

// 修改分页样式
.paginationClass {
  position: absolute;
  bottom: 12px;
  right: 14px;
  .el-pagination__total,
  .el-pagination__jump {
    color: #959abb;
  }
  .el-select--mini {
    margin-top: -10px;
  }
  .el-input__inner {
    // background-color: #0d102a;
    background-color: rgba(1, 15, 48, 0.3);
    border-color: #2a3259;
    color: #959abb;
  }
  .btn-prev,
  .el-pager .number,
  .btn-next {
    background-color: #0d102a;
  }
  .el-pager .number {
    color: #959abb;
  }
  .el-pager .number:hover {
    color: #fff;
  }
  .el-pager .active {
    color: #fff;
  }
  .btn-next:hover,
  .btn-prev:hover {
    color: #409eff;
  }
  .btn-next,
  .btn-prev {
    color: #fff;
  }
  button:disabled {
    color: #959abb;
    background-color: transparent;
  }
  .el-icon {
    background-color: transparent;
    color: #959abb;
  }
  .el-icon-d-arrow-right {
    color: #fff;
  }
  .el-icon:hover {
    color: #fff;
  }
  .el-icon-arrow-up:hover {
    color: #fff;
  }
}
// el-menu 折叠框隐藏
.customer-left-menu {
  .el-submenu__title {
    display: none !important;
  }
}
// 修改消息通知页面推送对象样式
.disabledArea.el-textarea.is-disabled .el-textarea__inner {
  background-color: #252950 !important;
}
// 修改推送对象穿梭组件样式
.transfer-left,
.transfer-right {
  background-color: #0e1233 !important;
  border: none !important;
  .transfer-title {
    background-color: #0e1233 !important;
    color: #fff !important;
    border-bottom: 1px solid #092749 !important;
  }
  .el-tree {
    background-color: #0e1233 !important;
    color: #fff;
    .el-tree-node.is-current {
      .el-tree-node__content {
        background-color: #2f356a !important;
      }
    }
    .el-tree-node:focus > .el-tree-node__content {
      background-color: transparent;
    }
    .el-tree-node__content {
      background-color: transparent;
    }
    .el-tree-node__content:hover,
    .el-tree-node__content:active {
      background-color: #2f356a;
    }
    .el-tree-node__content:visited {
      background-color: #0e1233;
    }
  }
}

混入的封装

index.js

// 表格通用方法
const listMixin = {
  name: 'mixin',
  data() {
    return {
      // 分页参数
      pagination: {
        page: 1,
        pageSize: 10,
      },
    }
  },
  computed: {
    defaultOption() {
      return {
        // 分页参数
        pagination: {
          page: 1,
          pageSize: 10,
        },
        step: 1, // 数值越大速度滚动越快
        limitMoveNum: 1, // 开始无缝滚动的数据量 this.tableData.length
        hoverStop: false, // 是否开启鼠标悬停stop
        direction: 1, // 0向下 1向上 2向左 3向右
        openWatch: true, // 开启数据实时监控刷新dom
        singleHeight: 60, // 单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1
        singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3
        waitTime: 1000, // 单步运动停止的时间(默认值1000ms)
      }
    },
    // 默认时间
    timeDefault() {
      const date = new Date()
      let defalutStartTime = date.getTime() - 0 * 24 * 3600 * 1000 // 转化为时间戳
      let defalutEndTime = date.getTime()
      const startDateNs = new Date(defalutStartTime)
      const endDateNs = new Date(defalutEndTime)
      // 月,日 不够10补0
      defalutStartTime =
        startDateNs.getFullYear() +
        '-' +
        (startDateNs.getMonth() + 1 >= 10
          ? startDateNs.getMonth() + 1
          : '0' + (startDateNs.getMonth() + 1)) +
        '-' +
        (startDateNs.getDate() >= 10 ? startDateNs.getDate() : '0' + startDateNs.getDate())
      defalutEndTime =
        endDateNs.getFullYear() +
        '-' +
        (endDateNs.getMonth() + 1 >= 10
          ? endDateNs.getMonth() + 1
          : '0' + (endDateNs.getMonth() + 1)) +
        '-' +
        (endDateNs.getDate() >= 10 ? endDateNs.getDate() : '0' + endDateNs.getDate())
      return [defalutStartTime, defalutEndTime]
    },
  },
  methods: {
    // 返回首页
    goBack() {
      if (sessionStorage.getItem('selectMenuValue')) {
        // 省级消息通知页和服务区投诉建议页的缓存
        sessionStorage.removeItem('selectMenuValue')
      }
      if (sessionStorage.getItem('searchData')) {
        sessionStorage.removeItem('searchData')
      }
      if (sessionStorage.getItem('searchPageIndex')) {
        sessionStorage.removeItem('searchPageIndex')
      }
      if (sessionStorage.getItem('searchPageSize')) {
        sessionStorage.removeItem('searchPageSize')
      }
      if (sessionStorage.getItem('reportMenu_scroll')) {
        sessionStorage.removeItem('reportMenu_scroll')
      }
      if (JSON.parse(localStorage.getItem('user')).restId) {
        this.$router.replace({ name: 'RestHome' })
      } else {
        this.$router.replace({ name: 'Home' })
      }
      // this.$router.push({ name: 'Home' })
    },
    // 查询
    search() {
      this.total = 0
      this.pageIndex = 1
      this.pagination.page = 1
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 切换每页显示的数量
    handleSizeChange(pagination) {
      this.pagination = pagination
      this.getDataList()
    },
    // 切换页码
    handleIndexChange(pagination) {
      this.pagination = pagination
      this.getDataList()
    },
    // 返回列表页并刷新
    // refreshDataList(val) {
    //   this.addOrUpdateVisible = false
    //   if (val) this.getDataList()
    // }
  },
}
export default listMixin

将以上三个文件挂在到main.js中

import listMixin from '@/util/mixin' // 查询分页
Vue.mixin(listMixin) // 混入 相当于选项合并

组件的使用

<template>
  <div>
    <div class="DR-right">
      <div class="DR-right-head">
        <base-elform
          label-width="0"
          :inline="true"
          :base-data="searchForm"
          :base-form="baseForm"
          :search-handle="searchHandle"
        />
      </div>
      <div class="DR-right-body">
        <base-list
          :list="list"
          :operates="operates"
          :total="total"
          :options="options"
          :pagination="pagination"
          :columns="columns"
          @handleSizeChange="handleSizeChange"
          @handleIndexChange="handleIndexChange"
        />
      </div>
    </div>
  </div>
</template>
<script>
import api from '@/api/data'
import baseList from './base-table/list'
import BaseElform from './base-form/elForm'
export default {
  components: {
    baseList,
    BaseElform,
  },
  data() {
    // 表单参数
    return {
      navLeft: {
        title: '卡口数据',
        icon: 'shujubaobiao',
      },
      isRestAuth: true,
      // 查询表单
      searchForm: {
        restId: '',
        restDirection: '',
        carType: '',
        carNo: '',
        isOut: '',
        startTime: null,
        endTime: null,
        selectTime: [],
      },
      exportOrTakeVisible: false,
      baseForm: [
        {
          type: 'Select',
          placeholder: '筛选服务区方向',
          prop: 'restDirection',
          clearable: true,
          options: [
            { value: '01', label: '方向1' },
            { value: '02', label: '方向2' },
          ],
        },
        {
          type: 'Input',
          placeholder: '请输入车牌号',
          clearable: true,
          prop: 'carNo',
        },
        {
          type: 'Select',
          placeholder: '筛选车辆类型',
          prop: 'carType',
          clearable: true,
          options: [],
        },
        {
          type: 'Select',
          placeholder: '是否驶离',
          clearable: true,
          prop: 'isOut',
          options: [
            { value: false, label: '否' },
            { value: true, label: '是' },
          ],
        },
        {
          type: 'Date',
          dateType: 'daterange',
          startPlaceholder: '选择开始时间',
          endPlaceholder: '选择结束时间',
          clearable: true,
          format: 'yyyy-MM-dd',
          prop: 'selectTime',
        },
      ],
      searchHandle: [
        {
          label: '搜索',
          round: 'round',
          show: true,
          class: 'searchButton',
          handle: () => {
            // 重置分页组件
            this.total = 0
            this.pageIndex = 1
            this.getDataList()
          },
        },
        {
          label: '导出',
          show: true,
          type: 'primary',
          handle: () => {
            this.excelOut()
          },
        },
      ],
      list: [],
      pageIndex: 1,
      pageSize: 10,
      total: 1,
      options: {},
      columns: [
        {
          prop: 'RestDirection',
          label: '服务区方向',
        },
        {
          prop: 'CarNo',
          label: '车牌号',
        },
        {
          prop: 'CarType',
          label: '车辆类型',
        },
        {
          prop: 'CarNoColor',
          label: '车牌颜色',
          showOverflowTooltip: true,
        },
        {
          prop: 'CarBrand',
          label: '车辆品牌',
          showOverflowTooltip: true,
        },
        {
          prop: 'CarColor',
          label: '车身颜色',
        },
        {
          prop: 'InTime',
          label: '入区时间',
        },
        {
          prop: 'OutTime',
          label: '离区时间',
        },
        {
          prop: 'stayTime',
          label: '在区时长(分)',
        },
      ],
//操作列
      operates: {
        width: 160,
        fixed: 'right',
        list: [
         {
            label: '编辑',
            type: 'text',
            show: () => {
              return true
            },
            method: row => {
              this.addOrUpdateHandle(row.restId)
            },
          },  {
            label: '删除',
            type: 'text',
            show: () => {
              return true
            },
            method: row => {
              this.deleteHandle(row.restId)
            },
          }]
      },
    }
  },
  mounted() {
    this.searchForm.selectTime = this.timeDefault
    this.searchForm.restId = JSON.parse(sessionStorage.getItem('store')).areaId
    this.getCarList()
    this.getreastdire()
    this.getDataList()
  },
  methods: {
    getCarList() {
      api.getCarTypeData(null).then(res => {
        if (res.code == '0' || res.code == 0) {
          this.baseForm[2].options = res.data
        } else {
          this.list = []
          this.total = 0
        }
      })
    },
    getreastdire() {
      let params = {
        restId: this.searchForm.restId,
      }
      api.getRestDirection(params).then(res => {
        if (res.code == '0' || res.code == 0) {
          this.baseForm[0].options = res.data
        } else {
          this.list = []
          this.total = 0
        }
      })
    },
    getDataList() {
      this.dataListLoading = true
      let params = {
        restId: this.searchForm.restId,
        restDirection: this.searchForm.restDirection,
        carNo: this.searchForm.carNo,
        carType: this.searchForm.carType,
        isOut: this.searchForm.isOut,
        page: this.pageIndex,
        pageSize: this.pageSize,
        startTime: this.searchForm.selectTime ? this.searchForm.selectTime[0] + ' 00:00:00' : null,
        endTime: this.searchForm.selectTime ? this.searchForm.selectTime[1] + ' 23:59:59' : null,
      }
      api.PostBayonetData(params).then(res => {
        if (res.code == '0' || res.code == 0) {
          this.list = res.data.list
          this.total = res.data.totalCount
        } else {
          this.list = []
          this.total = 0
        }
        this.dataListLoading = false
      })
    },
    handleSizeChange(pageObj) {
      this.pageIndex = pageObj.page
      this.pageSize = pageObj.pageSize
      this.getDataList()
    },
    handleIndexChange(pageObj) {
      this.pageIndex = pageObj.page
      this.pageSize = pageObj.pageSize
      this.getDataList()
    },
    // 导出
    excelOut() {
      window.location.href = `${api.baseUrl}/v1/rest/car/record/excel?restId=${
        this.searchForm.restId
      }&restDirection=${this.searchForm.restDirection}&carNo=${this.searchForm.carNo}&isOut=${
        this.searchForm.isOut
      }&carType=${this.searchForm.carType}&startTime=${
        this.searchForm.selectTime ? this.searchForm.selectTime[0] + ' 00:00:00' : ''
      }&endTime=${this.searchForm.selectTime ? this.searchForm.selectTime[1] + ' 23:59:59' : ''}`
    },
  },
}
</script>

1·基础案例

<template>
  <div class="DR-right">
    <div class="DR-right-head">
      <div class="sys_title">角色管理</div>
      <base-elform
        label-width="0"
        :inline="true"
        :base-data="searchForm"
        :base-form="baseForm"
        :search-handle="searchHandle"
      />
    </div>
    <div class="DR-right-body">
      <base-list
        :list="list"
        :operates="operates"
        :total="total"
        :options="options"
        :columns="columns"
        :pagination="pagination"
        @handleSizeChange="handleSizeChange"
        @handleIndexChange="handleIndexChange"
      />
    </div>
    <editDialog
      class="addUpdatedialog"
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
    ></editDialog>
  </div>
</template>
<script>
import api from '@/api/admin'
import editDialog from './role_AddOrUpdated.vue'
export default {
  components: { editDialog },
  props: {
    title: {
      type: String,
      default: '',
    },
  },
  data() {
    // 表单参数
    return {
      addOrUpdateVisible: false,
      // 查询表单
      searchForm: {
        roleName: '',
      },
      baseForm: [
        {
          type: 'Input',
          placeholder: '角色名称',
          clearable: true,
          prop: 'roleName',
        },
      ],
      searchHandle: [
        {
          label: '搜索',
          round: 'round',
          show: true,
          class: 'searchButton',
          handle: () => {
            // 重置分页组件
            this.total = 0
            // 点击查询回到第一页
            this.pagination.page = 1
            this.getDataList()
          },
        },
        {
          label: '新增',
          show: true,
          type: 'primary',
          handle: () => {
            this.addOrUpdateHandle()
          },
        },
      ],
      list: [],
      total: 1,
      options: {},
      columns: [
        {
          prop: 'roleId',
          label: 'ID',
        },
        {
          prop: 'roleName',
          label: '角色名称',
        },
        {
          prop: 'remark',
          label: '备注',
        },
        {
          prop: 'createTime',
          label: '创建时间',
        },
      ],
      operates: {
        width: 150,
        fixed: 'right',
        list: [
          {
            label: '编辑',
            type: 'text',
            show: () => {
              return true
            },
            method: row => {
              this.addOrUpdateHandle(row.roleId)
            },
          },
          {
            label: '删除',
            type: 'text',
            show: () => {
              return true
            },
            method: row => {
              this.deleteHandle(row.roleId, row.roleName)
            },
          },
        ],
      },
    }
  },
  mounted() {
    this.getDataList()
  },
  methods: {
    getDataList() {
      this.dataListLoading = true
      let params = {
        roleName: this.searchForm.roleName,
        page: this.pagination.page,
        pageSize: this.pagination.pageSize,
      }
      api.getRoleDataList(params).then(res => {
        this.dataListLoading = false
        if (res.code == '0' || res.code == 0) {
          this.list = res.page.list
          this.total = res.page.totalCount
        } else {
          this.list = []
          this.total = 0
        }
      })
    },
    addOrUpdateHandle(val) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(val)
      })
    },
    deleteHandle(id, roleName) {
      this.$confirm(`确定对角色名称为:[${roleName}]进行[删除]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          api.deleteRoleDataList(id).then(data => {
            if (data && data.code === 0) {
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.pagination.page = 1
                  this.getDataList()
                },
              })
            }
          })
        })
        .catch(() => {})
    },
  },
}
</script>

2·特殊案例

要是有一条数据需要展示图片:

使用基础的list应该这样配置

  columns: [
        {
          prop: 'name',
          label: '服务区名称',
        },
		............
        {
          prop: 'restPhoto',
          label: '服务区照片',
          render: (h, params) => {
            if (params.row.restPhoto && params.row.restPhoto !== '') {
              return h(
                'el-button',
                {
                  attrs: {
                    type: 'text',
                    size: 'small',
                  },
                  on: {
                    click: () => {
                      this.magnify(params.row.restPhoto)
                    },
                  },
                },
                '查看'
              )
            } else {
              return h(
                'el-link',
                {
                  props: {
                    type: 'info',
                    underline: false,
                  },
                },
                '-'
              )
            }
          },
        },
        {
          prop: 'thirdUrlPath',
          label: '第三方服务区平台链接',
        },
      ],
      methods:{
          // 点击查看放大图片
		    magnify(item) {
		      // console.log(item)
		      this.dialogMagnifyVisible = true
		      this.magnifyPhoto = item
		  },
     }

3·特殊案例3

 {
          prop: 'status',
          label: '状态',
          render: (h, params) => {
            return h('el-switch', {
              props: {
                value: params.row.status,
                activeValue: '1',
                inactiveValue: '0',
              },
              on: {
                change: () => {
                  this.changestatus(params.row)
                },
              },
            })
          },
        },
        {
          prop: '',
          label: '重置密码',
          render: (h, params) => {
            return h(
              'el-button',
              {
                attrs: {
                  type: 'text',
                  size: 'small',
                },
                on: {
                  click: () => {
                    this.restPassWords(params.row)
                  },
                },
              },
              '重置密码'
            )
          },
        },
		methods:{
		 changestatus(val) {
		      let params = {
		        userId: val.userId,
		        status: val.status === '1' ? '0' : '1',
		      }
		      api.updateUserStatus(params).then(res => {
		        if (res.code == 0) {
		          this.getDataList()
		        }
		      })
		    },
		}

4·特殊案例

一列中根据接口返回的不同状态展示不同的颜色

组件:

<template>
      <div class="DR-right-body">
        <base-elform
          style="margin-bottom:20px"
          label-width="0"
          :inline="true"
          :base-data="searchForm"
          :base-form="baseForm"
          :search-handle="searchHandle"
        />
        <base-list
          headerHeight="63vh"
          :list="list"
          :operates="operates"
          :total="total"
          :options="options"
          :columns="columns"
          :cellStyle="cellStyle"
          :show-pagination="paginationShow"
          @handleSizeChange="handleSizeChange"
          @handleIndexChange="handleIndexChange"
        />
      </div>
    </div>
</template>
<script>
  methods: {
 //重点代码
    cellStyle({ row, columnIndex }) {
      if (row.congestionType === '1' && columnIndex === 9) {
        return 'color: #16a692 '
      } else if (row.congestionType === '2' && columnIndex === 9) {
        return 'color: #c58d3b'
      } else if (row.congestionType === '3' && columnIndex === 9) {
        return 'color: #bd4337'
      } else {
        return
      }
    },
}
</script>
<style lang="scss" scoped>
.DR-right-head {
  display: flex;
  flex-wrap: wrap;
  height: 105px !important;
  box-sizing: border-box;
  .compaire {
    box-sizing: border-box;
    font-size: 20px;
    color: #33bee7;
    width: 100%;
    margin: 5px 0;
  }
  .left_container {
    width: 660px;
    height: 64px;
    background: #051134;
    .base-elform {
      margin-top: 10px;
      padding: 0 10px;
    }
  }
}
</style>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文