基于Vue+element-ui 的Table二次封装的实现


Posted in Javascript onJuly 20, 2018

本人第一次写这个 写的不好还望指出来

作为一个由于公司产品的升级然促使我从一个后端人员自学变成前端的开发人员 !

公司做的数据管理系统所以离不开表格了 然后表格样式统一啥的就想到封装一个element-ui 里面的table+Pagination了

效果图

基于Vue+element-ui 的Table二次封装的实现

表格组件的引入与使用

<com-table title="监测数据" v-model="tableData4" @selection-change="handleSelectionChange">
    <template>
     <el-table-column type="selection" width="55" align="center">
     </el-table-column>
     <el-table-column prop="name" label="表格名称" align="center">
     </el-table-column>
     <el-table-column label="测点" align="center">
      <template slot-scope="scope" v-if="scope.row.point.visible">
       <el-input v-model="scope.row.point.value" placeholder="请输入内容" @focus="focuspoint(scope.row.point)"></el-input>
      </template>
     </el-table-column>
     <el-table-column label="项目" align="center">
      <template slot-scope="scope" v-if="scope.row.item.visible">
       <el-input v-model="scope.row.item.value" placeholder="请输入内容" @focus="focusitem(scope.row.item)"></el-input>
      </template>
     </el-table-column>
    </template>
   </com-table>

使用插槽slot 使用起来就和原来的table一样了

import comTable from '@/components/common/com-table'
import { GetTempletExportList, GetTempletExportInfo } from '../../../api/transfer/index'
import ApiConfig from '@/api/ApiConfig'
export default {
 name: 'templet',
 components: {
  comTable
 },
 data() {
  return {
   tableData4: [],
   exporttableData: [],
   multipleSelection: [],
   currentpoint: null,
   currentitem: null,
   itemdialogshow: false,
   pointdialogshow: false,
   path: new ApiConfig().GetConfig().SysPath,
   checkeditem: [],//选中数据
  }
 },
 computed: {
  moduletype() {
   return this.$store.state.moduletype;
  },
  userinfo() {
   return this.$store.state.user.userInfo;
  }
 },
 watch: {
  moduletype() {
   this.init();
  }
 },
 created() {
  this.init();
 },
 methods: {
  init() {
   GetTempletExportList(this.userinfo.cityid, this.moduletype).then(re => {
    this.exporttableData = re.data;
    this.tableData4 = [];
    re.data.map(item => {
     this.tableData4.push({
      name: item.fldTableDesc,
      point: {
       visible: false,
       value: ''
      },
      item: {
       visible: true,
       value: item.ItemList
      }
     })
    })
   }, (error) => {
    this.$message({
     customClass: 'el-message_new',
     message: error,
     type: 'error'
    });
   })
  },
  handleSelectionChange(val) {
   console.log(val)
   this.multipleSelection = val;
  },
  focuspoint(val) {
   this.currentpoint = val;
  },
  focusitem(val) {
   this.currentitem = val;
   this.itemdialogshow = true;
  },
  itemconfirm() {
   this.itemdialogshow = !this.itemdialogshow;
  },
  itemhandleClose(done) {
   this.itemdialogshow = false;
  },
  ItemGroupSelectchange(val) {
   this.checkeditem = val;
   console.log(this.checkeditem);
   let groupitemcontent = [];
   val.map(item => {
    groupitemcontent.push(item.fldItemName);
   })
   this.currentitem.value = groupitemcontent.join(',');
  },
  submit() {
   if (this.multipleSelection.length > 0) {
    let message = "";
    let data = [];
    let name = "";
    this.multipleSelection.map((item, index) => {
     name = item.name;
     let str = item.name;
     let info = false;
     if (item.item.visible && item.item.value == "") {
      message += `表[${str}]请选择因子`;
      info = true;
     }
     if (item.point.visible && item.point.value == "") {
      if (info) {
       message += `、请选择测点/断面!`;
      } else {
       message += `表[${str}]请选择测点/断面!`;
      }
      info = true;
     }
     if (info) {
      message += "<br/>"
     }
     data.push({
      "AutoID": "1",
      "STCode": "",
      "PCode": "",
      "RCode": "",
      "RScode": "",
      "GDCODE": "",
      "type": this.moduletype,
      "itemcodeList": item.item.value.split(',').join('^'),
      "path": `${this.path.TempletExportSetting}${this.moduletype}.json`,
      "IsNeedNullData": "Y"
     })

    })
    if (message == "") {
     GetTempletExportInfo(data).then(re => {
      if (re.status == "ok") {
       var exportdata = eval((re.data));
       const { export_json_to_excel } = require("../../../libs/Export2Excel");
       if (exportdata[0].merg.length != 0) {
        var exdata = [];
        var itemlistUnit = [];
        var itemlistfldCharCode = [];
        for (var z = 0; z < exportdata[0].head.length - this.checkeditem.length; z++) {
         itemlistUnit.push(exportdata[0].head[z]);
         itemlistfldCharCode.push(exportdata[0].head[z])
        }
        this.checkeditem.map(item => {
         itemlistUnit.push(item.fldUnit);
         itemlistfldCharCode.push(item.fldCharCode);
        })
        var exdata = this.formatJson(exportdata[0].head, exportdata[0].data);
        exdata.unshift(itemlistUnit);
        exdata.unshift(itemlistfldCharCode);
        exdata.unshift(exportdata[0].head);
        console.log(exdata)
        exportdata[0].merg.push([0, 0, exportdata[0].head.length - 1, 0])
        export_json_to_excel([name], exdata, name, exportdata[0].merg);
       } else {
        var exdata = this.formatJson(exportdata[0].head, exportdata[0].data);
        exdata.unshift(exportdata[0].head);
        exportdata[0].merg.push([0, 0, exportdata[0].head.length - 1, 0])
        export_json_to_excel([name], exdata, name, exportdata[0].merg);
       }

      } else {
       this.$message({
        message: '导出失败!',
        type: 'error'
       });
      }
     })
    } else {
     this.$message({
      dangerouslyUseHTMLString: true,
      customClass: 'el-message_new',
      message: message,
      type: 'warning'
     });
    }
   } else {
    this.$message({
     customClass: 'el-message_new',
     message: '请先选择要导出的列表!',
     type: 'warning'
    });
   }
  },
  formatJson(filterVal, jsonData) {
   return jsonData.map(v =>
    filterVal.map(j => {
     return v[j];
    })
   );
  }
 }
}

comTable组件

<template>
 <div class="com-table">
  <div class="com-table-title" v-if="title">
   {{title}}
  </div>
  <div :class="[title?'com-table-content':'com-table-content-nottitle']">
   <el-table v-loading="loading" ref="multipleTable" stripe :data="tableData" style="width: 100%;" height="100%" border @selection-change="handleSelectionChange" @row-click="rowClick" @row-dblclick='rowDblclick' @cell-dblclick="celldblclick">
    <slot></slot>
   </el-table>
  </div>
  <div class="com-table-page">
   <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="PageIndex" :page-sizes="page_sizes" :page-size="Size" :layout="layout" :total="total">
   </el-pagination>
  </div>
 </div>
</template>
<script>
import commomway from '../../common/commonway.js' //分页
export default {
 name: 'com-table',
 props: {
  value: {//数据
   type: [Array, Object],
   default: () => {
    return [];
   }
  },
  PageSize: {//当前一页显示多少条数据
   type: Number,
   default: 20
  },
  page_sizes: {//分页规则
   type: Array,
   default: () => {
    return [1, 20, 40, 60, 80]
   }
  },
  current_page: {//当前所在页
   type: Number,
   default: () => {
    return 1;
   }
  },
  layout: {
   type: String,
   default: () => {
    return 'total, sizes, prev, pager, next, jumper';
   }
  },
  title: {//表格title
   type: String,
   default: () => {
    return '';
   }
  },
  loading: {
   type: Boolean,
   default: false
  }
 },
 data() {
  return {
   tableData: [],
   //页数索引  
   PageIndex: this.current_page,
   //每页显示的数量
   Size: this.PageSize,
   oldmultipleSelection: [],//旧的选中值
   multipleSelection: []//当前选中数据
  }
 },
 watch: {
  value(val) {
   this.getpagedata();
  },
  tableData(val) {
   // console.log(val);
  },
  multipleSelection(val, old) {
   this.oldmultipleSelection = old;
  }

 },
 mounted() {
  this.getpagedata();
 },
 computed: {
  total() {
   return this.value.length;
  }
 },
 methods: {
  //获得分页后的数据
  getpagedata() {
   var common = new commomway();
   this.tableData = common.pagination(this.PageIndex, this.Size, this.value, false);
   this.$emit("input", this.value);
   setTimeout(() => {//由于表格重新渲染延迟执行勾选
    this.toggleSelection(this.oldmultipleSelection)
   }, 20)

  },
  //点击每页显示数量时触发
  handleSizeChange: function (val) {
   this.Size = val;
   this.getpagedata();
   this.$emit('handleSizeChange', val);
  },
  //翻页的时候触发
  handleCurrentChange: function (val) {
   this.PageIndex = val;
   this.getpagedata();
   this.$emit('handleCurrentChange', val);

  },
  handleSelectionChange(val) {
   this.multipleSelection = val;
   this.$emit('selection-change', val);
  },
  toggleSelection(rows) {//勾选值
   if (rows) {
    rows.forEach(row => {
     this.$refs.multipleTable.toggleRowSelection(row);
    });
   } else {
    this.$refs.multipleTable.clearSelection();
   }
  },
  rowClick(row, event, column){
    this.$emit('row-click', row, event, column);
  },
  celldblclick(row, column, cell, event){
   this.$emit('cell-dblclick', row, column, cell, event);
  },
  rowDblclick(row,enent){
   //console.log(row,enent)
  }
 }
}
</script>
<style lang="sass">
 @import "./com-table.scss";
</style>

commonway.js

class CommonWay {
 /**
  * description:对数组的分页处理
  * author:bilimumu
  * date:2017-10-28 
  * @param {number} [pageNo=1] 页码
  * @param {number} [pageSize=10] 每页显示条数 
  * @param {any} [obj=[]] 待分页的数组
  * @param {Boolean} [iscreateNewdata=true] 是否创建新的数据
  * @returns 返回新的数组
  * @memberof CommonWay
  */
 pagination(pageNo = 1, pageSize = 10, obj = [], iscreateNewdata = true) {
  var array = [];
  if (iscreateNewdata) {
   array = JSON.parse(JSON.stringify(obj));
  } else {
   array = obj;
  }
  var offset = (pageNo - 1) * pageSize;
  return (offset + pageSize >= array.length) ? array.slice(offset, array.length) : array.slice(offset, offset + pageSize);
 }
}

export default CommonWay

com-table.scss

.com-table {
 height: 100%;
 width: 100%;
 &-title {
  color: #FFF;
  background: #42A2F5;
  padding: 0;
  font-size: 15px;
  height: 40px;
  line-height: 40px;
  text-indent: 8px;
 }
 &-content {
  width: 100%;
  height: calc(100% - 40px - 55px);
 }
 &-content-nottitle {
  width: 100%;
  height: calc(100% - 55px);
 }
 &-page {
  height: 55px;
  width: 100%;
  background: #EFF3F8;
  display: flex;
  align-items: center;
  justify-content: center;
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
海量经典的jQuery插件集合
Jan 12 Javascript
关于js注册事件的常用方法
Apr 03 Javascript
div+css+js实现无缝滚动类似marquee无缝滚动兼容firefox
Aug 29 Javascript
jquery delay()介绍及使用指南
Sep 02 Javascript
node.js中的fs.createReadStream方法使用说明
Dec 17 Javascript
基于JavaScript实现一定时间后去执行一个函数
Dec 14 Javascript
使用BootStrap进行轮播图的制作
Jan 06 Javascript
node.js入门教程之querystring模块的使用方法
Feb 27 Javascript
最常用的jQuery表单验证(简单)
May 23 jQuery
深入理解React Native原生模块与JS模块通信的几种方式
Jul 24 Javascript
认识jQuery的Promise的具体使用方法
Oct 10 jQuery
微信小程序自定义带价格显示日历效果
Dec 29 Javascript
webpack+vue-cil中proxyTable处理跨域的方法
Jul 20 #Javascript
详解vue-cli官方脚手架配置
Jul 20 #Javascript
Vue中的异步组件函数实现代码
Jul 20 #Javascript
vue 中的keep-alive实例代码
Jul 20 #Javascript
Angularjs实现页面模板清除的方法
Jul 20 #Javascript
搭建vue开发环境
Jul 19 #Javascript
jQuery实现表单动态添加数据并提交的方法
Jul 19 #jQuery
You might like
PHP 循环删除无限分类子节点的实现代码
2013/06/21 PHP
php加密算法之实现可逆加密算法和解密分享
2014/01/21 PHP
php面向对象中的魔术方法中文说明
2014/03/04 PHP
一个经典的PHP验证码类分享
2014/11/18 PHP
TP5框架简单登录功能实现方法示例
2019/10/31 PHP
javascript模仿msgbox提示效果代码
2008/06/10 Javascript
jQuery UI Dialog控件中的表单无法正常提交的解决方法
2010/12/19 Javascript
js常用代码段整理
2011/11/30 Javascript
上传的js验证(图片/文件的扩展名)
2013/04/25 Javascript
jQuery自带的一些常用方法总结
2014/09/03 Javascript
JavaScript的arguments对象应用示例
2014/09/15 Javascript
js中的关联数组与普通数组详解
2016/07/27 Javascript
使用Javascript判断浏览器终端设备(PC、IOS(iphone)、Android)
2017/01/04 Javascript
详解win7 cmd执行vue不是内部命令的解决方法
2017/07/27 Javascript
layui 富文本赋值,取值,取纯文本值的实例
2019/09/18 Javascript
Vue3 源码导读(推荐)
2019/10/14 Javascript
JS实现动态无缝轮播
2020/01/11 Javascript
JS遍历树层级关系实现原理解析
2020/08/31 Javascript
Vue中ref和$refs的介绍以及使用方法示例
2021/01/11 Vue.js
[01:05:56]Liquid vs VP Supermajor决赛 BO 第二场 6.10
2018/07/04 DOTA
Python爬虫实例_城市公交网络站点数据的爬取方法
2018/01/10 Python
python解压TAR文件至指定文件夹的实例
2019/06/10 Python
Python中zip函数如何使用
2020/06/04 Python
Python同时处理多个异常的方法
2020/07/28 Python
python源文件的字符编码知识点详解
2021/03/04 Python
英国领先的奢侈品零售商之一:CRUISE
2016/12/02 全球购物
python+selenium小米商城红米K40手机自动抢购的示例代码
2021/03/24 Python
vue实现倒计时功能
2021/03/24 Vue.js
医药工作者的求职信范文
2013/09/21 职场文书
计算机专业个人求职自荐信
2013/09/21 职场文书
施工安全标语
2014/06/07 职场文书
法制宣传标语
2014/06/23 职场文书
助人为乐道德模范事迹材料
2014/08/16 职场文书
工作批评与自我批评范文
2014/10/16 职场文书
给老师的感谢信
2015/01/20 职场文书
Django操作cookie的实现
2021/05/26 Python