vue管理系统列表行按钮过多, 封装更多组件

2023-09-22 11:21:48

管理系统table列表操作列, 随着按钮的数量越来越多会不断加宽操作列, 感觉很不好, 对此我封装了这个自动把多余的按钮放到更多菜单下

MoreOperation/index.vue
menu组件我这是ant的, 可以自行替换为其他框架的

<template>
  <div class="table-operations-group">
    <template v-if="btns">
      <div class="option-btn-wrap" v-for="(item, index) in outerBtns" :key="index" @click="clickBtn(item)" :class="{ 'disabled': item.disabled === true }">
        <slot v-if="item.customRender" :name="item.customRender" v-bind="item">
          <div class="my-text-btn">{{ item.name }}</div>
        </slot>
        <div v-else class="my-text-btn">
          {{ item.name }}
        </div>
      </div>
    </template>

    <template v-if="!btns">
      <div class="option-btn-wrap" v-for="(item, index) in outerBtns" :key="index" @click="clickBtn(item)" :class="{ 'disabled': item.disabled === true }">
        <component :is="slotNode(item.vnode)" />
      </div>
    </template>

    <div class="option-btn-wrap" v-if="moreBtns.length > 0">
      <a-dropdown>
        <div class="my-text-btn">
          更多
          <a-icon type="down" />
        </div>
        <a-menu slot="overlay" @click="dropdownMenu">
          <a-menu-item v-for="(item, index) in moreBtns" :key="index" :disabled="item.disabled">
            {{ item.name }}
          </a-menu-item>
        </a-menu>
      </a-dropdown>
    </div>
  </div>
</template>

<script>
/**
 * MoreOperation 组件
 * 1. 配置模式
 * 2. slot模式
 * @author chengxg
 * @since 2023-09-15
 */

let weekTableMap = new WeakMap()
import OperationItem, { MoreOperationItemProp } from "./OperationItem.vue"

// 根据模版创建对象
function createObjByTpl(obj, tpl) {
  let newObj = {}
  for (let f in tpl) {
    if (typeof obj[f] === 'undefined') {
      newObj[f] = tpl[f]
    } else {
      newObj[f] = obj[f]
    }
  }
  return newObj
}
export { OperationItem }

export default {
  name: 'MoreOperation',
  comments: {},
  props: {
    // 表格所有数据
    tableData: {
      type: Array,
      default: null
    },
    // 表格行数据
    row: {
      type: Object,
      required: true,
      default: null
    },

    // 配置模式 所有的按钮
    btns: {
      type: Array,
      // [MoreOperationItemProp]
      default: null
    },

    // 外边的按钮数量
    outerBtnNum: {
      type: Number,
      default: 2
    }
  },
  provide() {
    return {
      'moreOperations': this
    };
  },
  data() {
    return {
      items: []
    }
  },
  computed: {
    activeBtns() {
      let btns = this.btns || this.items || []
      return btns.filter((item) => {
        if (typeof item.disabled === 'function') {
          item.disabled = item.disabled(this.row, item.params)
        }
        if (typeof item.show === 'function') {
          return item.show(this.row, item.params)
        }
        return true
      })
    },
    outerBtns() {
      if (this.activeBtns.length <= this.outerBtnNum + 1) {
        return this.activeBtns
      }
      return this.activeBtns.slice(0, this.outerBtnNum)
    },
    moreBtns() {
      if (this.activeBtns.length <= this.outerBtnNum + 1) {
        return []
      }
      return this.activeBtns.slice(this.outerBtnNum)
    }
  },
  watch: {

  },
  created() {
    this.updateSlotBtns()
    this.autoCalcMaxWidth()
    this.$watch(() => {
      return this.row
    }, (newVal, oldVal) => {
      this.$nextTick(() => {
        this.updateSlotBtns()
        this.$nextTick(() => {
          this.autoCalcMaxWidth()
        })
      })
    })
  },
  methods: {
    // 计算当前列最大宽度
    autoCalcMaxWidth() {
      if (!this.row) {
        return
      }
      let width = 0
      for (let item of this.outerBtns) {
        width += item.width
      }
      // more 宽度60
      if (this.moreBtns.length > 1) {
        width += 60
      }
      this.row.btnsMaxWidth = width
      this.calcOperationWidth()
    },
    // 计算表格操作列的最大宽度
    calcOperationWidth() {
      let tableData = this.tableData || this.$parent.tableData
      if (!tableData) {
        return
      }
      if (weekTableMap[tableData]) {
        clearTimeout(weekTableMap[tableData])
      }
      weekTableMap[tableData] = setTimeout(() => {
        let maxWidth = 120;
        for (const row of tableData) {
          if (row.btnsMaxWidth > maxWidth) {
            maxWidth = row.btnsMaxWidth;
          }
        }
        let operatorColumnWidth = maxWidth + 10;
        this.$emit("update:operatorWidth", operatorColumnWidth)
        // 使用vxeTable组件库 自动调整最大操作列 列宽
        if (this.$parent.$parent.recalculate) {
          this.$parent.$parent.recalculate(true)
        }
      }, 10)
    },

    clickBtn(item) {
      item.click && item.click(this.row, item.params)
    },
    dropdownMenu(command) {
      let btnItem = this.moreBtns[command.key]
      if (btnItem && typeof btnItem.click === 'function') {
        btnItem.click(this.row, btnItem.params)
      }
    },

    updateSlotBtns() {
      if (!this.btns) {
        if (this.$slots.default) {
          this.items = this.$slots.default.filter((item) => {
            if (item && item.componentOptions && item.componentOptions.tag == 'OperationItem') {
              return true
            }
            return false
          }).map((item) => {
            let obj = createObjByTpl(item.componentOptions.propsData, MoreOperationItemProp)
            if (item.componentOptions.propsData.item) {
              Object.assign(obj, item.componentOptions.propsData.item)
            }
            obj.vnode = item
            return obj
          })
        } else {
          this.items = []
        }
      }
    },

    slotNode(vnode) {
      return {
        render(h) {
          return vnode;
        }
      }
    },
  },
  mounted() {

  }
}
</script>

<style lang="scss">
.table-operations-group {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .option-btn-wrap {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    cursor: pointer;
    user-select: none;

    &::after {
      display: block;
      content: ' ';
      width: 0;
      height: 14px;
      border-left: 1px solid #eeeeee;
      margin: 0 4px;
    }

    &:last-child {
      &::after {
        display: none;
      }
    }

    &.disabled {
      pointer-events: none;

      .my-text-btn {
        cursor: no-drop;
        color: #bfc2cc;

        &:active {
          background: none;
        }
      }
    }
  }

  .my-text-btn {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    user-select: none;
    border-radius: 1px;
    padding: 3px 5px;
    height: 30px;
    vertical-align: middle;

    font-size: 14px;
    font-weight: 400;
    color: #3471ff;

    &:active {
      background: rgba(29, 111, 255, 0.06);
    }

    &.disabled {
      cursor: no-drop;
      color: #bfc2cc;

      &:active {
        background: none;
      }
    }

    .btn-icon {

      i,
      &.el-icon,
      &.icon-svg,
      &.svg-icon {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        margin-right: 4px;
        width: 12px;
        height: 12px;
      }
    }

    .btn-icon-right {

      i,
      &.el-icon,
      &.icon-svg,
      &.svg-icon {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        margin-right: 4px;
        width: 12px;
        height: 12px;
      }
    }
  }
}
</style>

MoreOperation/OperationItem.vue

<script>
export const MoreOperationItemProp = {
  name: "", // 按钮名
  width: 50, // 按钮所占的宽度
  params: null, // show, click, disabled 传入的第二个参数
  // 是否显示回调
  show: (row, params) => {
    return true
  },
  // 点击回调
  click: (row, params) => {

  },
  // 是否禁用, 可以为函数
  disabled: false,
  // 配置模式下的自定义渲染slot
  customRender: ""
}

export default {
  name: 'OperationItem',
  props: {
    name: {
      type: String,
      default: ""
    },
    width: {
      type: Number,
      default: 50
    },
    params: {
      default: null
    },
    show: {
      type: Function,
      default: null
    },
    click: {
      type: Function,
      default: null
    },
    disabled: {
      type: [Boolean, Function],
      default: false
    },

    // 对象形式赋值
    item: {
      type: Object,
      default: null // MoreOperationItemProp
    }
  },
  data() {
    return {

    }
  },
  computed: {

  },
  watch: {

  },
  created() {

  },
  render(h) {
    if (!this.$slots.default) {
      let btnName = this.name
      if (this.item && this.item.name) {
        btnName = this.item.name
      }
      return h('div', {
        class: 'my-text-btn'
      }, btnName)
    }
    return this.$slots.default
  },
  methods: {

  },
  beforeDestroy() {

  }
}
</script>

使用方法:

实现了配置模式和slot模式, slot模式支持v-if来控制按钮显示隐藏

            <!-- 1. 配置模式 -->
            <MoreOperation :btns="operationBtns" :row="row" :operatorWidth.sync="operatorColumnWidth">
              <template #del="item">
                <div class="my-text-btn" style="color:red;">{{ item.name }}</div>
              </template>
            </MoreOperation>

            <!-- 2. slot模式 -->
            <MoreOperation :row="row" :operatorWidth.sync="operatorColumnWidth">
              <OperationItem name="详情" :click="operationBtns[0].click"></OperationItem>
              <OperationItem v-if="operationBtns[1].show(row)" :width="80" name="历史记录" :click="operationBtns[1].click"></OperationItem>
              <OperationItem v-if="operationBtns[2].show(row)" :width="50" name="删除" :click="operationBtns[2].click">
                <div class="my-text-btn" style="color:red;">删除</div>
              </OperationItem>
              <OperationItem :item="operationBtns[3]"></OperationItem>
              <OperationItem :item="operationBtns[4]"></OperationItem>
              <OperationItem v-if="operationBtns[5].show(row)" :width="50" name="禁用" :click="operationBtns[5].click"></OperationItem>
              <OperationItem :item="operationBtns[6]"></OperationItem>
            </MoreOperation>
import MoreOperation, { OperationItem } from "@/components/MoreOperation/index.vue"

export default {
  name: "example",
  components: { MoreOperation, OperationItem },
  data() {
    return {
      loading: false,
      searchForm: {
        name: "",
      },
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      }, // 分页信息
      tableData: [],
      operatorColumnWidth: 120,
      operationBtns: [{
        name: "详情",
        width: 45,
        params: null,
        show: (row, params) => {
          return Math.random() > 0.1
        },
        click: (row, params) => {
          console.log("click 详情")
        },
        disabled: false,
        customRender: ""
      }, {
        name: "删除",
        width: 45,
        params: null,
        show: (row, params) => {
          return Math.random() > 0.5
        },
        click: (row, params) => {
          console.log("click 删除")
        },
        disabled: false,
        customRender: "del",
      }, {
        name: "历史记录",
        width: 80,
        show: (row) => {
          return Math.random() > 0.8
        },
        click: (row) => {
          console.log("click 历史记录")
        },
      }, {
        name: "修改",
        width: 45,
        show: (row) => {
          return Math.random() > 0.5
        },
        click: (row) => {
          console.log("click 修改")
        },
        disabled: true
      }, {
        name: "撤回",
        width: 45,
        show: (row) => {
          return Math.random() > 0.5
        },
        click: (row) => {
          console.log("click 撤回")
        }
      }, {
        name: "禁用",
        width: 45,
        show: (row) => {
          return Math.random() > 0.5
        },
        click: (row) => {
          console.log("click 禁用")
        }
      }, {
        name: "流程跟踪",
        width: 80,
        show: (row) => {
          return Math.random() > 0.8
        },
        click: (row) => {
          console.log("click 流程跟踪")
        },
        disabled: true
      }],
    };
  },
  created() {

  },
  mounted() {
    this.onSearch()
  },
  methods: {
    onSearch(page = {}) {
      if (this.loading) {
        return
      }

      let params = {
        ...this.searchForm,
        ...this.page,
        ...page,
      }

      this.loading = true
      this.fetchData(params).then((data) => {
        this.loading = false
        this.tableData = data.list
        updatePageInfo(this.page, data)
        this.showBtn = true
        setTimeout(() => {
          // this.showBtn = false
        }, 2000)
      }).catch((err) => {
        this.loading = false
        this.tableData = []
      })
    },

    fetchData(params) {
      return new Promise((resolve, reject) => {
        let data = dataListPage({
          name: "@cname",
          "sex|1": ["男", "女"],
          age: "@natural(1, 100)",
          city: "@city",
          hobby: "@csentence(2, 10)",
          createName: "@cname",
          createTime: "@date",
        }, params).data
        console.log(data)
        resolve(data)
      })
    },

  }
}

效果图

更多推荐

中国核动力研究设计院使用 DolphinDB 替换 MySQL 实时监控仪表

随着仪表测点的大幅增多和采样频率的增加,中国核动力研究设计院仪控团队原本基于MySQL搭建的旧系统已经无法满足大量数据并发写入、实时查询和聚合计算的需求。他们在研究DB-Engines时序数据库榜单时了解到国内排名第一的DolphinDB。经过测试,发现其非常符合业务需求,并且在2022年1月正式选择了DolphinD

2023年全国研究生数学建模竞赛华为杯C题大规模创新类竞赛评审方案研究

2023年全国研究生数学建模竞赛华为杯C题大规模创新类竞赛评审方案研究原题再现:现在创新类竞赛很多,其中规模较大的竞赛,一般采用两阶段(网评、现场评审)或三阶段(网评、现场评审和答辩)评审。创新类竞赛的特点是没有标准答案,需要评审专家根据命题人(组)提出的评审框架(建议)独立评审。所以,对同一份作品,不同评委的评分可能

MySQL 开源证书真比 Postgres 更能带动社区吗?

笔者之前写的「全方位对比Postgres和MySQL」还在持续发酵,最近腾讯的公众号也发布了一篇「MySQLVSPostgreSQL,谁是世界上最成功的数据库?」,其中在对比两者使用的开源证书时写到:PostgreSQLLicense是一个宽松的开源许可证,类似于MIT许可证。它允许用户自由使用、修改和分发,无需公开源

go迷之切片截取分析

切片截取,有没有很迷?目录典型截取(两参数、三参数)及分析迷之append参与截取及细节分析关于截取时的初始索引是否从第一个位置开始的影响修改原切片细节分析典型截取(两参数、三参数)及分析先看一个例子来表示一下切片截取(仅截取,无append):a:=[]int{1,2}a0:=a[0:1]fmt.Printf("a0

UI设计和平面设计的区别是什么?看完这篇一次搞懂

很多想要从事视觉领域工作的新手设计师,搞不懂UI设计和平面设计的区别;也有很多平面设计师工作后想转UI,却不知道该如何进行,导致择业和职业发展受阻,其实核心问题还是因为没有弄清楚UI设计和平面设计的区别是什么。这里先说明,UI设计和平面设计,是两个完全不同的设计领域。UI设计师着重于解决产品的用户习惯和易用体验,而平面

07JVM_内存模型和CAS与原子类

一、内存模型1.java内存模型Java内存结构是JMM(JavaMemoryModel)的意思。JMM定义了一套在多线程读写共享数据(成员变量,数组)时,对数据的原子性,见性,有序性的规则和保障。1.1原子性什么是原子性?原子性是指一个操作是不可中断的,即使多个线程一起执行,一个线程一旦开始,就不会被其他线程干扰。如

Django系列:Django开发环境配置与第一个Django项目

Django系列Django开发环境配置与第一个Django项目作者:李俊才(jcLee95):https://blog.csdn.net/qq_28550263邮箱:291148484@163.com本文地址:https://blog.csdn.net/qq_28550263/article/details/1328

自动化测试—选择器

根据id选择名字:<inputtype="text"id='searchtext'/>element=wd.find_element(By.CSS_SELECTOR,'#searchtext')element.send_keys('你好')根据class选择元素的两种方式:1.By.CLASS_NAME:element

form组件的封装(element ui ) 简单版本

当你使用Vue.js构建Web应用时,封装可复用组件是提高开发效率和代码可维护性的关键之一。在这篇文章中,我们将探讨如何使用Vue.js来创建一个通用的表单组件,以及如何将它封装成一个可配置的组件。实现思路拿下表单模板一个个的改造(文本,下拉,单选,复选等)按钮默认值的设定rules规则的处理创建通用的form组件这段

Arm机密计算架构技术(Armv9 CCA) 白皮书

1.概述在本篇文章中,我们将介绍机密计算(ConfidentialComputing)在现代计算平台中扮演的角色,并解释机密计算的原理。然后我们将说明Arm机密计算架构(ArmCCA)如何在Arm计算平台中实现机密计算。看完本文后,您将能够:定义机密计算描述复杂的系统信任链了解Realm(机密领域)是由ArmCCA引入

网络安全进阶学习第十八课——业务逻辑漏洞(附录:不同行业业务逻辑的漏洞)

文章目录一、互联网行业二、P2P金融行业三、电商行业四、政务行业总结一、互联网行业通用业务模块业务逻辑漏洞登录暴力破解用户名密码撞库验证码爆破和绕过、手机号撞库、账户权限绕过注册恶意用户批量注册、恶意验证注册账户、存储型XSS密码找回重置任意用户账户密码、批量重置用户密码、新密码劫持、短信验证码劫持、用户邮箱劫持篡改后

热文推荐