vue+element常用的表格表单封装

一、常用表单

示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。

<template>
  <div style="width:100%;height:100%;" id="ManualAddId">
    <div>
      <div class="el-table el-table--fit el-table--border el-table--enable-row-transition">
        <el-form style="width: 100%;" size="medium" :model="form" ref="form" :rules="rules">
          <table class="el-table__header" id="perCrudID" style="width: 100%;" cellspacing="0" cellpadding="0"
                 border="0">
            <tr class="el-table__row">
              <td class="col-th" colspan="6">
                <el-divider content-position="left">网络设备</el-divider>
              </td>
            </tr>
            <tr class="el-table__row">
              <td class="col-th">
                <div class="cell">设备序列号</div>
              </td>
              <td colspan="2">
                <el-form-item prop="devNum">
                  <el-input placeholder="请输入设备序列号" class="input_width" v-model="form.devNum" :disabled="disabledNum">
                  </el-input>
                </el-form-item>
              </td>
              <td class="col-th">
                <div class="cell">设备位置</div>
              </td>
              <td colspan="2">
                <el-form-item prop="location">
                  <el-cascader class="input_width" v-model="form.location" :options="locationInfo" placeholder="请选择设备所在位置"
                               size="small" :props="defaultProps" :clearable="true" :show-all-levels="false">
                  </el-cascader>
                </el-form-item>
              </td>
            </tr>
            <tr class="el-table__row">
              <td class="col-th">
                <div class="cell">设备类别</div>
              </td>
              <td colspan="2">
                <el-form-item prop="devType">
                  <el-select placeholder="请输入设备类别" size="medium"  class="input_width"  clearable
                             v-model="form.devType" @change="changeMethod"  :disabled="disabledNum">
                    <el-option v-for="item in devTypeInfo" :key="item.value" :label="item.label" :value="item.value"
                               filterable>
                    </el-option>
                  </el-select>
                </el-form-item>
              </td>
              <td class="col-th">
                <div class="cell">设备型号</div>
              </td>
              <td colspan="2">
                <el-form-item prop="devModel">
                  <el-select  placeholder="请输入设备型号(须选择设备类别)"
                             size="medium"  class="input_width"  clearable v-model="form.devModel"  :disabled="disabledNum">
                    <el-option v-for="item in devModelInfo" :key="item" :label="item" :value="item" filterable>
                    </el-option>
                  </el-select>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="col-th">
                <div class="cell">版本号</div>
              </td>
              <td colspan="2">
                <el-form-item prop="version">
                  <el-select  class="input_width"  placeholder="请选择版本号" size="medium" clearable v-model="form.version"  :disabled="disabledNum">
                    <el-option v-for="(value,key) in versionInfo" :key="key" :label="value" :value="value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </td>
              <td class="col-th">
                <div class="cell">出厂日期</div>
              </td>
              <td colspan="2">
                <el-form-item prop="factoryDate">
                  <el-date-picker class="input_width" v-model="form.factoryDate" type="date" value-format="yyyy-MM-dd"
                                  placeholder="请选择出厂日期" :picker-options="pickerOptions1"  :disabled="disabledNum">
                  </el-date-picker>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <td class="col-th">
                <div class="cell">设备IP地址</div>
              </td>
              <td colspan="2">
                <el-form-item prop="devIP">
                  <el-input class="input_width" placeholder="请输入正确的设备IP地址(IPV4格式)" v-model="form.devIP">
                  </el-input>
                </el-form-item>
              </td>
            </tr>
          </table>
        </el-form>
      </div>
    </div>
    <div class="but_style">
      <el-button size="medium" type="primary" @click="manualRegistrationMethod('form')">保存</el-button>
      <el-button size="medium" type="plain" @click="cancelMethod">取消</el-button>
    </div>
  </div>
</template>

<script>
var iplist = /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))|\*)((\/([012]\d|3[012]|\d))?)(,((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))|\*)((\/([012]\d|3[012]|\d))?))*$/
var ipduan = /^(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))-(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))$/;
export default {
  props: ['internettype', 'modelDate'],
  data() {

    var checkdevNum = (rule, value, callback) => {
      if (this.modelDate.type == 'add') {
        if (!value) {
          return callback(new Error('编号不能为空!'));
        } else {
          if (value.length > 40) {
            callback(new Error('输入内容长度不能大于40个字符!'));
          } else {
            this.$http.get(this.isOrNoOnlyUrl  + '/' + value,).then((response) => {
                if (response.data == true) {
                  callback();
                } else {
                  callback(new Error('编号已存在!'));
                }
              },
              (error) => {
                callback();
              });
          }
        }
      } else {
        callback();
      }
    };
    var checkdevType = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('设备类别不能为空!'));
      } else {
        if(value.length > 30) {
          callback(new Error('输入内容长度不能大于30个字符!'));
        } else {
          callback();
        }
      }
    };
    var checkversion = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('设备版本号不能为空!'));
      } else {
        if(value.length > 30) {
          callback(new Error('输入内容长度不能大于30个字符!'));
        } else {
          callback();
        }
      }
    };
    var checkdevlocation = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('设备位置不能为空!'));
      } else {
        if(value.length > 30) {
          callback(new Error('输入内容长度不能大于30个字符!'));
        } else {
          callback();
        }
      }
    };
    var checkdevModel = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('设备型号不能为空!'));
      } else {
        if(value.length > 30) {
          callback(new Error('输入内容长度不能大于30个字符!'));
        } else {
          callback();
        }
      }
    };
    var checkfactoryDate = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('日期不能为空!'));
      } else {
        callback();
      }
    };
    var checkdevIP = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('ip地址不能为空!'));
      } else {
        let iparr = value.trim().split(",");
        //判断ipv4
        for (let i = 0; i < iparr.length; i++) {
          let ip4 = !iplist.test(iparr[i])
          let ipduans = !ipduan.test(iparr[i])
          // let ip6 = !ipv6.test(iparr[i])
          if (ip4 && ipduans) {
            callback(new Error("用户IP格式不正确"));
          } else {
            callback()
          }
        }
      }
    };
    return {
      // 手动注册
      manualRegistrationUrl: this.baseJson.baseUrl + this.baseJson.devmngtmicroService + '/deviceRegistration/manualRegistration',
      // 查询下拉框
      getDevPartUrl: this.baseJson.baseUrl + this.baseJson.devmngtmicroService + '/devType/getDevPart',
      // 查询区域接口
      findAllLabelTreeUrl: this.baseJson.baseUrl + this.baseJson.devmngtmicroService + '/deviArea/labelSeetingPart',
      // 分页查询
      registeredUrl: this.baseJson.baseUrl + this.baseJson.devmngtmicroService + '/deviceRegistration/registered',
      // 点击更新查询表单
      registeredSingleUrl: this.baseJson.baseUrl + this.baseJson.devmngtmicroService + '/deviceRegistration/registeredSingle',
      // 验证编号是否唯一
      isOrNoOnlyUrl: this.baseJson.baseUrl + this.baseJson.devmngtmicroService + '/deviceRegistration/isOrNoOnly',
      rules: {
        devNum: [{
          validator: checkdevNum,
          trigger: 'blur'
        }],
        devType: [{
          validator: checkdevType,
          trigger: 'change'
        }],
        devModel: [{
          validator: checkdevModel,
          trigger: 'change'
        }],
        version: [{
          validator: checkversion,
          trigger: 'change'
        }],
        factoryDate: [{
          validator: checkfactoryDate,
          trigger: 'change'
        }],
        devIP: [{
          validator: checkdevIP,
          trigger: 'change'
        }],
        location: [{
          validator: checkdevlocation,
          trigger: 'change'
        }],
      },
      form: {
        type: 'internet',
        devNum: '',
        devType: '',
        devModel: '',
        version: '',
        factoryDate: '',
        devIP: '',
        location: '',
        port: '',
      },
      devTypeInfo: [],
      devTypeAndDevModel: {},
      devModelInfo: [],
      versionInfo: [],
      locationInfo: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        value: 'code',
        emitPath: false,
      },
      numMarked: '',
      disabledNum: false
    }
  },
  components: {},
  mounted() {
  },

  methods: {
// 取消方法
    cancelMethod() {
      this.$emit('listCancel', true)
      this.$refs.form.resetFields()
    },
// 保存方法
    manualRegistrationMethod(form) {
      this.disabledNum=true;
      if (this.modelDate.type == 'update') {
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.$http.post(this.manualRegistrationUrl, this.form, {
              _timeout: 3000
            }).then((response) => {
                if (response.data.result) {
                  this.$message({
                    showClose: true,
                    type: 'success',
                    message: '更新成功!'
                  });
                  this.$emit('lismanualadd', true);
                } else {
                  this.$message({
                    showClose: true,
                    message: '更新失败!',
                    type: 'error'
                  });
                }
              },
              (error) => {
                this.$message({
                  showClose: true,
                  message: '网络连接失败!',
                  type: 'error'
                });
              });
          } else {
            return false;
          }
        });
      }
      if (this.modelDate.type == 'add') {
        this.disabledNum=false;
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.$http.post(this.manualRegistrationUrl, this.form, {
              _timeout: 3000
            }).then((response) => {
                if (response.data.result) {
                  this.$message({
                    showClose: true,
                    type: 'success',
                    message: '添加成功!'
                  });
                  this.$emit('lismanualadd', true);
                } else {
                  this.$message({
                    showClose: true,
                    message: '添加失败!',
                    type: 'error'
                  });
                }
              },
              (error) => {
                this.$message({
                  showClose: true,
                  message: '网络连接失败!',
                  type: 'error'
                });
              });
          } else {
            return false;
          }
        });
      }
    },
    // 查询下拉框
    getallSelectMethod() {
      this.$http.get(this.getDevPartUrl, {
        _timeout: 3000
      }).then((response) => {
        this.devTypeAndDevModel = response.data.devTypeAndDevModel;
        this.devTypeInfo = response.data.devTypeAndName;
        this.versionInfo = response.data.version;
      })
        .catch(function (response) {
          this.$message({
            showClose: true,
            message: '网络连接失败!',
            type: 'error'
          });
        })
    },
    // 点击更新查询表单
    registeredSingleMethod() {
      this.$http.get(this.registeredSingleUrl + '/' + this.modelDate.row.type + '/' + this.modelDate.row.devNum, {
        _timeout: 3000
      }).then((response) => {
        this.form = response.data;
        this.$http.get(this.getDevPartUrl, {
          _timeout: 3000
        }).then((response) => {
          this.devTypeAndDevModel = response.data.devTypeAndDevModel;
          this.devModelInfo = this.devTypeAndDevModel[this.form.devType]
        })
          .catch(function (response) {
            this.$message({
              showClose: true,
              message: '网络连接失败!',
              type: 'error'
            });
          })
      })
        .catch(function (response) {
          this.$message({
            showClose: true,
            message: '网络连接失败!',
            type: 'error'
          });
        })
    },
    getSelectData() {
      this.$http.get(this.findAllLabelTreeUrl, {
        _timeout: 3000
      }).then((response) => {
          this.locationInfo = response.data;
        },
        (error) => {
          this.loading = false;
          this.$message({
            showClose: true,
            message: '网络连接失败!',
            type: 'error'
          });
        });
    },

  }
}
</script>

<style scoped>
.input_width {
  width: 100%;
}
.cell {
  font-weight: bold;
  text-align: center;
  border-collapse: collapse;
}

.but_style {
  margin-top: 20px;
  text-align: center;
}
/*表格内边距*/
.el-table td,
.el-table th {
  padding: 8px 8px;
}
/*给验证留下位置*/
#ManualAddId .el-form-item {
  margin-bottom: 8px;
}
</style>

二、常用表格

代码如下(示例):

<template>
	<div id="personMngtId" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" class="loadingDiv">
		<div class="headCls">
			<div class="titleImgDiv">
				<img class="titleImg" :title="version" src="../res/per.png">
			</div>
			<div class="titleCls">人员管理</div>
			<el-button type="primary" class='addbut' size="mini" icon="el-icon-plus" @click='addMethod' v-if='addbut'>新增</el-button>
		</div>

		<div class="tabDiv" v-if='personshow'>
			<div class="queryDivClass">
				<span>部门:</span>
				<el-cascader class="queryInput" v-model="selectedOptions" id="elCascader" :options="deptInfo" placeholder="请选择部门" size="small" :props="defaultProps" :clearable="true" :show-all-levels="false" @change="changeDeptMethod">
				</el-cascader>
				&nbsp;
				<span>编号:</span>
				<el-input class="queryInput" v-model="perNumber" placeholder="请输入人员编号" size="small" clearable></el-input>
				&nbsp;
				<span>姓名:</span>
				<el-input class="queryInput" v-model="perName" placeholder="请输入人员姓名" size="small" clearable></el-input>
				&nbsp;
				<span>状态:</span>
				<el-select class="queryInput" v-model="state" placeholder="请选择人员状态" size="small" clearable>
					<el-option v-for="(value,key) in stateInfo" :key="key" :label="value" :value="key">
					</el-option>
				</el-select>
				&nbsp;
				<el-button type="primary" size="mini" @click='getAllMethod' v-if='querybut' icon="el-icon-search">查询</el-button>
				&nbsp;
				<el-button type="primary" size="mini" @click='dialogFormVisible = true' v-if='exportbut' icon="el-icon-download" :disabled="isClickExport">{{isClickExport == true?'正在导出':'导出'}}<i class="el-icon-loading" v-if="isClickExport"></i></el-button>
				<!--<el-button class="queryBut" type="primary" size="mini" @click='dialogFormVisible = true' v-if='exportbut' icon="el-icon-download">导出</el-button>-->
				&nbsp;
			</div>

			<div class="tableClass" id="personIdDiv">
				<el-table class="tab" :data="tableData" border :row-class-name="tableRowClassName">
					<el-table-column label="序号" align="center" type="index" :index="indexMethod" width="65" label-class-name="labelClass"> </el-table-column>
					<el-table-column prop="num" label="编号" align="center" min-width="60" label-class-name="labelClass">
					</el-table-column>
					<el-table-column prop="name" label="姓名" header-align="center" min-width="75" label-class-name="labelClass">
						<template slot-scope="scope">
							<div v-if="scope.row.state === '1'" class="stateDiv">
								<img src="../res/perstation1.png" title="在职" class="stateImg"> {{scope.row.name}}
								<!--<span style="background-color: orange">{{scope.row.name}}</span>-->
							</div>
							<div v-else-if="scope.row.state === '2'" class="stateDiv">
								<img src="../res/perstation2.png" title="离职" class="stateImg">
								<!--{{scope.row.name}}-->
								<span style="color: red">{{scope.row.name}}</span>
							</div>
							<!--<div v-else-if="scope.row.state === '3'">
								<img src="../res/perstation3.png" title="注销" style="vertical-align:top; width:25%; height:25%;">{{scope.row.name}}
							</div>-->
						</template>
					</el-table-column>
					<el-table-column prop="sex" label="性别" align="center" min-width="40" label-class-name="labelClass">
					</el-table-column>
					<el-table-column prop="phone" label="手机号" min-width="70" align="center" label-class-name="labelClass"></el-table-column>
					<el-table-column prop="deptNum" label="所属部门" align="center" min-width="120" label-class-name="labelClass">
						<template slot-scope="scope">
							<div :title="scope.row.deptNames==null?deptMsg[scope.row.deptNum]:scope.row.deptNames">{{deptMsg[scope.row.deptNum]}}</div>
						</template>
					</el-table-column>
					<!--<el-table-column prop="email" label="邮箱" align="center" min-width="100" label-class-name="labelClass">
					</el-table-column>-->
					<el-table-column prop="state" label="状态" align="center" min-width="40" label-class-name="labelClass">
						<template slot-scope="scope">
							{{stateInfo[scope.row.state]}}
						</template>
					</el-table-column>
					<el-table-column label="操作" min-width="120" v-if="isShow" align="center" label-class-name="labelClass">
						<template slot-scope="scope">
							<el-button size="mini" v-if='querybut' type="info" @click="queryMethod(scope.row)">查看</el-button>
							<el-button size="mini" v-if='updatebut' type="primary" @click="updateMethod(scope.row)">更新</el-button>
							<el-button size="mini" v-if="deletebut" type="danger" @click="deleteMethod(scope.$index,scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!--分页begin-->
				<div class="paging" v-if="pageShow">
					<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-sizes="[5, 10,15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageTotal">
					</el-pagination>
				</div>
			</div>
			<!--分页end-->
		</div>
		<el-dialog :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
			<el-card shadow="never">
				<div class="titleLegend">标题</div>
				<div class="titleLegend2">
					<el-form :model="form2" :rules="rules2" ref="form2" label-width="80px" label-position="left">
						<el-form-item label="标题名称" prop="title">
							<el-input v-model="form2.title" placeholder="请输入标题名称" clearable></el-input>
						</el-form-item>
					</el-form>
				</div>
			</el-card>
			<el-card shadow="never">
				<div class="titleLegend">选择列</div>
				<div class="titleLegend2">
					<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" style="text-align: left;">全选</el-checkbox>
					<div class="checkboxDiv">
						<el-checkbox-group v-model="checkedColumns" @change="handleCheckedCitiesChange">
							<el-checkbox v-for="value,key in columnOptions" :label="key" :key="key" :id="key">{{value}}</el-checkbox>
						</el-checkbox-group>
					</div>
				</div>
			</el-card>

			<div slot="footer" class="dialog-footer">
				<el-button size="medium" type="primary" @click="exportMethod('form2')">导出</el-button>
				<el-button size="medium" @click="cancelMethod('form2')">取 消</el-button>
			</div>
		</el-dialog>

		<div v-if="!personshow" class="crudDiv">
			<PersonCrud :clickParam="clickParam" @lisData="lisData"></PersonCrud>
		</div>

	</div>
</template>

<script>
	import CookieUtil from '@/common/util/CookieUtil'
	import version from '../res/version.js'
  // 导出哪些字段点按钮的时候
	const Options = {
		num: '编号',
		name: '名称',
		deptNum: '所属部门',
		sex: '性别',
		nation: '民族',
		address: '住址',
		degree: '学历',
		birth: '出生日期',
		idCardNum: '身份证号',
		major: '专业',
		graduateSchool: '毕业院校',
		phone: '手机号',
		contacts: '联系人',
		contactsPhone: '联系人手机号',
		email: '邮箱',
		state: '状态',
	};

	export default {
		components: {
			'PersonCrud': () =>
				import('@/components/HrPlugin/view/PersonCrud'),
		},
		data() {
			var checkTitle = (rule, value, callback) => {
				if(!value) {
					return callback(new Error('请输入标题!'));
				} else {
					callback();
				}
			};
			return {
				version: version.getVersion(),
				//加载
				loading: true,
				//请求url
				getAllUrl: this.baseJson.baseUrl + this.baseJson.hrmicroService + '/person/findAllByPage',
				getSelectsUrl: this.baseJson.baseUrl + this.baseJson.hrmicroService + '/person/getMap',
				deleteUrl: this.baseJson.baseUrl + this.baseJson.hrmicroService + '/person/deleteByNum',
				exportPerMsgUrl: this.baseJson.baseUrl + this.baseJson.hrmicroService + '/person/exportPerMsg',

				stateInfo: {},
				deptInfo: [], //部门级联
				defaultProps: {
					value: 'num',
					label: 'deptName',
					children: 'children',
				},
				deptMsg: '', //部门Map,key为num,value为name
				clickParam: {}, //点击新增/查看/更新传递的参数

				departPermissions: [], //部门权限
				addDepartPermissions: [],
				queryDepartPermissions: [],
				toImgUrl: this.PersonBaseUrl + "/personnel/findImageToBytes",

				//按钮设置
				addbut: false,
				updatebut: false,
				querybut: false,
				deletebut: false,
				exportbut:true ,

				personshow: true,
				tableData: [],
				//查询条件
				selectedOptions: [],
				deparNumber: '', //选择查询的部门参数
				perNumber: '',
				perName: '',
				state: '',
				//分页
				pageShow: false,
				pageTotal: 0, //总共条数
				pageSize: 10, //每页多少条
				currentPage: 1, //当前第几页

				//点击查看界面中的返回按钮和更新界面中的取消按钮用于回显
				currentPage2: 1,
				deparNumber2: '',
				perNumber2: '',
				perName2: '',
				state2: '',
				selectedOptions2: [],
				//是否点击查看,编辑
				isClick: false,
				//是否修改条件
				queryParam: false,

				//导出
				columnOptions: Options,
				checkAll: false,
				checkedColumns: [],
				isIndeterminate: true,
				dialogFormVisible: false,
				filterVal: [], //表值

				queryCriteria: [], //查询条件
				form2: {
					title: '' //标题
				},
				rules2: {
					title: [{
						validator: checkTitle,
						trigger: 'blur'
					}]
				},
				//功能权限
				isShow: false,
				isClickExport: false,
			}
		},
		mounted() {
			var funPoint = eval('(' + sessionStorage.getItem('funPoint') + ')');
			var funNum = eval('(' + sessionStorage.getItem('funNum') + ')');

			for(var key in funPoint) {
				if(key == funNum) {
					for(var i = 0; i < funPoint[key].length; i++) {
						if(funPoint[key][i].name == '查询') {
							this.isShow = true;
							this.querybut = true;
						}

						if(funPoint[key][i].name == '新增') {
							this.isShow = true;
							this.addbut = true;
						}
						if(funPoint[key][i].name == '更新') {
							this.isShow = true;
							this.updatebut = true;
						}
						if(funPoint[key][i].name == '删除') {
							this.isShow = true;
							this.deletebut = true;
						}
						if(funPoint[key][i].name == '导出') {
							this.isShow = true;
							this.exportbut = true;
						}
					}
				}
			}
			this.getSelectsMethod();
			this.getAllMethod();
		},
		watch: {
			perNumber: {
				handler: function(val, oldval) {
					this.queryParam = true;
				},
				deep: true
			},
			perName: {
				handler: function(val, oldval) {
					this.queryParam = true;
				},
				deep: true
			}
		},
		methods: {
			cancelMethod(formName) {
				this.dialogFormVisible = false;
				this.form2.title = '';
				this.$refs[formName].resetFields();
				this.checkAll = false;
				this.checkedColumns = [];
			},
			//全选
			handleCheckAllChange(val) {
				this.checkedColumns = val ? Object.keys(this.columnOptions) : [];
				this.isIndeterminate = false;
				this.filterVal = Object.keys(this.columnOptions);
			},
			handleCheckedCitiesChange(value) {
				this.filterVal = value;
				var length = Object.keys(this.columnOptions).length;
				let checkedCount = value.length;
				this.checkAll = checkedCount === length;
				this.isIndeterminate = checkedCount > 0 && checkedCount < length;
			},
			//导出
			exportMethod(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {
						//表头集合不能为空
						if(this.filterVal.length > 0) {
							this.dialogFormVisible = false;
							this.isClickExport = true;
							var mapVal = {};
							for(var i = 0; i < this.filterVal.length; i++) {
								mapVal[this.filterVal[i]] = this.columnOptions[this.filterVal[i]];
							}
							//							alert(JSON.stringify(mapVal))
							var param = {
								title: this.form2.title, //标题
								queryCriteria: {
									deptNum: this.deparNumber,
									num: this.perNumber,
									name: this.perName,
									state: this.state
								}, //查询条件
								columnNameMap: mapVal, //表头属性组成的map集合
								columnNameList: this.filterVal, //表头属性组成的List集合
							};

							var fileName = this.form2.title + ".xls" //下载的文件;
							var that = this;
							var xhr = new XMLHttpRequest();
							xhr.timeout = 3000;
							xhr.open('post', that.exportPerMsgUrl, true);
							xhr.setRequestHeader('content-type', 'application/json');
							xhr.setRequestHeader("Authorization", "Bearer " + CookieUtil.mutations.getCookie("accessToken"));
							//可以将`xhr.responseType`设置为`"blob"`也可以设置为`" arrayBuffer"`
							//xhr.responseType = 'arrayBuffer';
							xhr.responseType = 'blob';

							xhr.onload = function(e) {
								if(this.status == 200) {
									const blob = this.response;
									if('download' in document.createElement('a')) { // 非IE下载
										const elink = document.createElement('a')
										elink.download = fileName;
										elink.style.display = 'none';
										elink.href = URL.createObjectURL(blob);
										document.body.appendChild(elink);
										elink.click();
										URL.revokeObjectURL(elink.href) // 释放URL 对象
										document.body.removeChild(elink)
										that.isClickExport = false;
										that.form2.title = '';
										that.$refs[formName].resetFields();
										that.checkAll = false;
										that.checkedColumns = [];
										that.filterVal = [];
									} else { // IE10+下载
										navigator.msSaveBlob(blob, fileName)
									}
								} else if(this.status == 404) {
									var tip = decodeURIComponent(xhr.getResponseHeader('tip')); //未找到的文件名称
									if(tip != null) {
										that.isClickExport = false;
										that.$message({
											showClose: true,
											message: tip,
											type: 'error'
										});
									}
								} else {
									that.isClickExport = false;
									that.$message({
										showClose: true,
										message: '导出失败!',
										type: 'error'
									});
								}
							};
							xhr.send(JSON.stringify(param));

						} else {
							return false;
						}
					}
				});
			},
			tableRowClassName({
				row,
				rowIndex
			}) {
				if(row.state == "2") {
					return 'warning-row';
				} else {
					return '';
				}
			},
			//分割字符串
			splitMethod: function(strarr, str) {
				var newarr = new Array();
				var arr = strarr.split(str);
				for(var i = 0; i < arr.length; i++) {
					newarr.push(arr[i]);
				}
				return newarr;
			},
			//选择查询部门
			changeDeptMethod: function(value) {
				this.queryParam = true;
				this.deparNumber = value[value.length - 1];
				if(this.deparNumber == undefined) {
					this.deparNumber = "";
				}
			},
			//序号
			indexMethod: function(index) {
				return(this.currentPage - 1) * this.pageSize + (index + 1);
			},
			//分页
			handleSizeChange: function(val) {
				this.pageSize = val;
				this.getAllMethod();
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getAllMethod();
			},
			//查询下拉框信息
			getSelectsMethod: function() {
				this.$http.get(this.getSelectsUrl, {
						_timeout: 3000
					}).then((response) => {
						this.stateInfo = response.data.stateInfo;
						this.deptInfo = response.data.deptInfo;
						console.log(this.deptInfo)
						this.deptMsg = response.data.deptMsg;
					})
					.catch(function(response) {
						this.$message({
							showClose: true,
							message: '网络连接失败!',
							type: 'error'
						});
					})
			},
			//列表
			getAllMethod: function() {
				//分两种情况:
				//1.点击查看或更新后返回到列表页面时,返回点击前的页码
				//2.只要查询条件改变每次都是返回第一页
        // 一般页面没有这个是第二种情况
				if(this.isClick == true) {
					//回显
					this.currentPage = this.currentPage2;
					this.deparNumber = this.deparNumber2;
					this.perNumber = this.perNumber2;
					this.perName = this.perName2;
					this.selectedOptions = this.selectedOptions2;
					this.state = this.state2;
				} else {
					if(this.queryParam == true) { //查询条件改变
						this.currentPage = 1;
					}
				}
				this.isClick = false;
				this.queryParam = false;
				var param = {
					pageSize: this.pageSize,
					currentPage: this.currentPage,
					deptNum: this.deparNumber,
					num: this.perNumber,
					name: this.perName,
					state: this.state
				};
				this.$http.get(this.getAllUrl + '/' + encodeURIComponent(JSON.stringify(param)), {
						_timeout: 3000
					}).then((response) => {
						if(response.data.perList.length > 0) {
							this.pageShow = true;
						}
						// 返回的数据,返回的总条数
						this.tableData = response.data.perList;
						this.pageTotal = response.data.totalElements;
						this.loading = false;
					})
					.catch(function(response) {
						this.loading = false;
						this.$message({
							showClose: true,
							message: '网络连接失败!',
							type: 'error'
						});
					})
			},
			addMethod: function() {
				this.clickParam = {
					type: "add"
				};
				this.personshow = false;
				this.addbut = false;
			},
			queryMethod: function(row) {
				this.clickParam = {
					type: "query",
					num: row.num
				};
				this.personshow = false;
				this.addbut = false;
				this.isClick = true;
				this.currentPage2 = this.currentPage;
				this.deparNumber2 = this.deparNumber;
				this.perNumber2 = this.perNumber;
				this.perName2 = this.perName;
				this.state2 = this.state;
				this.selectedOptions2 = this.selectedOptions;
			},
			updateMethod: function(row) {
				this.clickParam = {
					type: "update",
					num: row.num
				};
				this.personshow = false;
				this.addbut = false;
				this.isClick = true;
				this.currentPage2 = this.currentPage;
				this.deparNumber2 = this.deparNumber;
				this.perNumber2 = this.perNumber;
				this.perName2 = this.perName;
				this.state2 = this.state;
				this.selectedOptions2 = this.selectedOptions;
			},
			deleteMethod: function(index, row) {
				this.$confirm('确认删除  “' + row.name + '” ?', "提示", {
					confirmButtonText: "确认",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => {
					this.$http.delete(this.deleteUrl + "/" + row.num, {
							_timeout: 3000
						})
						.then((response) => {
							if(response.data == true) {
								this.$message({
									showClose: true,
									type: 'success',
									message: '删除成功!'
								});
								this.tableData.splice(index, this.tableData.length);
								this.getAllMethod();
							} else {
								this.$message({
									showClose: true,
									message: '删除失败!',
									type: 'error'
								});
							}
						})
						.catch(function(response) {
							this.$message({
								showClose: true,
								message: '网络连接失败!',
								type: 'error'
							});
						})
				}).catch(() => {
					return false;
				})
			},
			lisData: function(data) {
				if(data == true) {
					var funPoint = eval('(' + sessionStorage.getItem('funPoint') + ')');
					var funNum = eval('(' + sessionStorage.getItem('funNum') + ')');
					for(var key in funPoint) {
						if(key == funNum) {
							for(var i = 0; i < funPoint[key].length; i++) {
								if(funPoint[key][i].name == '查询') {
									this.isShow = true;
									this.querybut = true;
								}

								if(funPoint[key][i].name == '新增') {
									this.isShow = true;
									this.addbut = true;
								}
								if(funPoint[key][i].name == '更新') {
									this.isShow = true;
									this.updatebut = true;
								}
								if(funPoint[key][i].name == '删除') {
									this.isShow = true;
									this.deletebut = true;
								}
								if(funPoint[key][i].name == '导出') {
									this.isShow = true;
									this.exportbut = true;
								}
							}
						}
					}
					this.personshow = true;
					this.getAllMethod();
					this.getSelectsMethod();
				}
			},
		}
	}
</script>

<style scoped>
	@import '../../../common/css/index.css';
	.loadingDiv {
		height: 100%;
		width: 100%;
	}

	.stateDiv {
		text-align: left;
	}

	.stateImg {
		vertical-align: middle;
		width: 26px;
		height: 26px;
	}

	.addbut {
		margin: 5px 4px 0px 0px;
		float: right;
	}

	.queryDivClass {
		text-align: left;
		margin: 0px 0px 5px 5px;
	}

	.tabDiv {
		margin-top: 8px;
	}

	.tab {
		width: 99%;
		margin-left: 5px;
	}

	.queryInput {
		width: 15%;
	}

	.crudDiv {
		margin: 5px 0 0 0;
		padding: 0 5px;
	}

	.fieldsetClass {
		margin: 5px 0 5px 0;
		border-left: none;
		border-right: none;
		border-bottom: none;
		border-top: none;
	}

	.titleLegend {
		font-size: 15px;
		font-weight: bold;
		text-align: left;
	}

	.titleLegend2 {
		text-align: left;
		margin: 12px 0 0 0;
	}
</style>
<style>
	.queryDivClass .el-cascader-menu__item--extensible::after {
		right: 8px;
	}
	#personMngtId .el-table .warning-row {
		background: #DDE7F6;
	}
	.checkboxDiv .el-checkbox__label {
		width: 65px;
		line-height: 26px;
	}
</style>





你可能感兴趣的:(vue表单表格,elementui,前端,vue.js)