基于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 相关文章推荐
JS 页面内容搜索,类似于 Ctrl+F功能的实现代码
Aug 13 Javascript
js 变量类型转换常用函数与代码[比较全]
Dec 01 Javascript
使用JavaScript 实现各种跨域的方法
May 08 Javascript
js HTML5上传示例代码完整版
Oct 10 Javascript
jquery设置css样式的多种方法(总结)
Feb 21 Javascript
原生js简单实现放大镜特效
May 16 Javascript
详解webpack2+React 实例demo
Sep 11 Javascript
集合Bootstrap自定义confirm提示效果
Sep 19 Javascript
Vue实现动态添加或者删除对象和对象数组的操作方法
Sep 21 Javascript
javascript实现图片轮播代码
Jul 09 Javascript
vue实现将一个数组内的相同数据进行合并
Nov 07 Javascript
TypeScript实用技巧 Nominal Typing名义类型详解
Sep 23 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
DC《神奇女侠2》因疫情推迟上映 温子仁新恐怖片《恶性》撤档
2020/04/09 欧美动漫
php实现比较全的数据库操作类
2015/06/18 PHP
php实现数组中索引关联数据转换成json对象的方法
2015/07/08 PHP
Yii2中OAuth扩展及QQ互联登录实现方法
2016/05/16 PHP
Laravel构建即时应用的一种实现方法详解
2017/08/31 PHP
TP框架实现上传一张图片和批量上传图片的方法分析
2020/04/23 PHP
防止网站内容被拷贝的一些方法与优缺点好处与坏处分析
2007/11/30 Javascript
jQuery对象和DOM对象的相互转化实现代码
2010/03/02 Javascript
JavaScript操作XML 使用百度RSS作为新闻源示例
2012/02/17 Javascript
JS中的substring和substr函数的区别说明
2013/05/07 Javascript
JavaScript中创建字典对象(dictionary)实例
2015/03/31 Javascript
百度地图api如何使用
2015/08/03 Javascript
浅析jquery数组删除指定元素的方法:grep()
2016/05/19 Javascript
JavaScript中的子窗口与父窗口的互相调用问题
2017/02/08 Javascript
Nodejs实现文件上传的示例代码
2017/09/26 NodeJs
Vue.js更改调试地址端口号的实例
2018/09/19 Javascript
vue中使用WX-JSSDK的两种方法(推荐)
2020/01/18 Javascript
vue制作toast组件npm包示例代码
2020/10/29 Javascript
使用vue编写h5公众号跳转小程序的实现代码
2020/11/27 Vue.js
Python操作Mysql实例代码教程在线版(查询手册)
2013/02/18 Python
Python使用SocketServer模块编写基本服务器程序的教程
2016/07/12 Python
keras:model.compile损失函数的用法
2020/07/01 Python
Python实现随机爬山算法
2021/01/29 Python
收集的7个CSS3代码生成工具
2010/04/17 HTML / CSS
HTML5 audio标签使用js进行播放控制实例
2015/04/24 HTML / CSS
英国健康和美容技术产品购物网站:CurrentBody
2019/07/17 全球购物
物业管理公司实习生自我鉴定
2013/09/19 职场文书
图书室管理制度
2014/01/19 职场文书
暑期培训心得体会
2014/09/02 职场文书
导航工程专业自荐信
2014/09/02 职场文书
纪念九一八事变演讲稿:忘记意味着背叛
2014/09/14 职场文书
个人四风问题对照检查材料思想汇报
2014/10/06 职场文书
夫妻忠诚协议书范本
2014/11/17 职场文书
个人事迹材料怎么写
2014/12/30 职场文书
2016应届毕业生实习评语
2015/12/01 职场文书
年会邀请函的格式及范文五篇
2019/11/02 职场文书