可修改新增表格

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <!-- import CSS -->
    <link
      rel="stylesheet"
      href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"
    />
  </head>
  <body>
    <div id="app">
      <el-button type="primary" @click="addListItem(0)" size="mini"
        >添加</el-button
      >
      <el-table
        :data="model.slice?model.slice((currentPage-1)*5,currentPage*5):[]"
        :current-page.sync="currentPage"
        style="width: 100%"
      >
        <el-table-column prop="userName" label="用户姓名" width="180">
        </el-table-column>
        <el-table-column prop="phoneNumber" label="电话号码" width="180">
        </el-table-column>
        <el-table-column prop="email" label="email"> </el-table-column>
        <el-table-column prop="genderType" label="性别">
          <template slot-scope="scope">
            <span> {{ scope.row.genderType ==1?'男':'女'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="password" label="密码"> </el-table-column>
        <el-table-column prop="birthday" label="生日"> </el-table-column>
        <el-table-column prop="updateTime" label="更新时间"> </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="addListItem(scope.row)" type="text" size="small">
              修改
            </el-button>
            <span
              class="el-tag el-tag--danger el-tag--mini"
              style="cursor: pointer"
              @click="deleteList(scope)"
            >
              删除
            </span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-size="5"
        layout="prev, pager, next"
        :total="model.length"
        @current-change="current_change"
      >
      </el-pagination>
      <el-dialog
        :title="isUpdate?'修改数据':'新增数据'"
        :visible.sync="dialogVisible"
        width="30%"
      >
        <section class="form-area">
          <el-form
            :model="dynamicValidateForm"
            ref="dynamicValidateForm"
            label-width="100px"
            class="demo-dynamic"
          >
            <el-form-item
              prop="userName"
              label="用户名"
              :rules="rules.userName"
            >
              <el-input v-model="dynamicValidateForm.userName"></el-input>
            </el-form-item>
            <el-form-item
              prop="phoneNumber"
              label="电话号码"
              :rules="rules.phoneNumber"
            >
              <el-input v-model="dynamicValidateForm.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱" :rules="rules.email">
              <el-input v-model="dynamicValidateForm.email"></el-input>
            </el-form-item>
            <el-form-item
              prop="genderType"
              label="性别"
              :rules="rules.genderType"
            >
              <el-select
                v-model="dynamicValidateForm.genderType"
                placeholder="请选择性别"
                style="width: 100%"
              >
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="密码" prop="password" :rules="rules.password">
              <el-input
                type="password"
                v-model="dynamicValidateForm.password"
                autocomplete="off"
                style="width: 100%"
              ></el-input>
            </el-form-item>
            <el-form-item prop="birthday" label="生日" :rules="rules.birthday">
              <el-date-picker
                type="date"
                placeholder="请选择生日"
                v-model="dynamicValidateForm.birthday"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="submitForm('dynamicValidateForm')"
                >提交</el-button
              >
              <el-button @click="dialogVisible=false">取消</el-button>
            </el-form-item>
          </el-form>
        </section>
      </el-dialog>
      <el-dialog
        title="提示"
        :visible.sync="centerDialogVisible"
        width="30%"
        center
      >
        <span>是否删除?</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="cancelForm">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </body>
  <!-- import Vue before Element -->
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <!-- import JavaScript -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <script>
    var getNowFormatDate = (date) => {
      var date = date instanceof Date ? date : new Date(date);
      var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    };
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|5|7|8|9][0-9]{9}$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        // Number.isInteger是es6验证数字是否为整数的方法,但是我实际用的时候输入的数字总是识别成字符串
        // 所以我就在前面加了一个+实现隐式转换
        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };
    new Vue({
      el: "#app",
      data: function () {
        // 可以把校验规则单独提出一个js文件 通过export方式导
        // 写在这里是为了此篇博客的展示
        var validatePass = (rule, value, callback) => {
          if (value === "") {
            callback(new Error("请输入用户名"));
          }
          if (value) {
            let allName = [];
            let hasName = false;
            this.model.forEach((el, ind) => {
              allName.push(el.userName);
            });
            let realInd = this.model.findIndex((el) => {
              return el.id === this.updateInd;
            });
            console.log(allName.indexOf(value));
            console.log(realInd);
            if (
              this.isUpdate &&
              allName.indexOf(value) != -1 &&
              allName.indexOf(value) != realInd
            ) {
              hasName = true;
            }
            if (!this.isUpdate && allName.indexOf(value) != -1) {
              hasName = true;
            }
            // 用写死value的方式 模拟接口请求
            if (hasName) {
              callback(new Error("用户名已经存在"));
            } else {
              callback();
            }
          }
        };
        return {
          isUpdate: false,
          tableId: 0,
          centerDialogVisible: false,
          updateInd: null,
          dynamicValidateForm: {
            userName: "",
            phoneNumber: "",
            email: "",
            genderType: "",
            password: "",
            birthday: "",
            updateTime: "",
          },
          dialogVisible: false,
          pagesize: 5,
          currentPage: 1,
          deleteRow: {},
          // list数据
          model: [],
          newModel: [],
          // 表头字段
          tableHeadData: [
            {
              name: "userName",
              width: 210,
              label: "用户姓名",
            },
            {
              name: "phoneNumber",
              width: 160,
              label: "电话号码",
            },
            {
              name: "email",
              width: 210,
              label: "email",
            },
            {
              name: "genderType",
              width: 160,
              label: "性别",
            },
            {
              name: "password",
              width: 160,
              label: "密码",
            },
            {
              name: "birthday",
              width: 160,
              label: "生日",
            },
            {
              name: "updateTime",
              width: 300,
              label: "更新时间",
            },
          ],
          // 下拉选项判断条件
          // 校验规则
          rules: {
            userName: [
              {
                required: true,
                message: "用户名不能为空",
                trigger: "blur",
              },
              { validator: validatePass, trigger: ["blur", "change"] },
            ],
            phoneNumber: [
              { required: true, message: "请输入电话号码", trigger: "blur" },
              {
                validator: checkPhone,
                message: "请输入正确的电话号码",
                trigger: ["blur", "change"],
              },
            ],
            genderType: [
              {
                required: true,
                message: "性别不能为空",
                trigger: ["blur", "change"],
              },
            ],
            email: [
              {
                required: true,
                message: "请输入邮箱地址",
                trigger: ["blur", "change"],
              },
              {
                type: "email",
                message: "请输入正确的邮箱地址",
                trigger: ["blur", "change"],
              },
            ],
            password: [
              {
                required: true,
                message: "密码不能为空",
                trigger: ["blur", "change"],
              },
            ],
            birthday: [
              {
                required: true,
                message: "生日不能为空",
                trigger: ["blur", "change"],
              },
            ],
          },
        };
      },
      watch: {
        model: {
          handler(val, old) {
            if (val.length)
              localStorage.setItem("TableList", JSON.stringify(val));
          },
          deep: true,
          immediate: true,
        },
      },
      mounted() {
        // 模拟接口请求赋值

        let newData = [
          {
            id: 1,
            userName: "11",
            phoneNumber: "13554099888",
            email: "11@qq.com",
            genderType: "1",
            password: "1",
            birthday: "1",
            updateTime: "Y",
            genderTypeList: [
              { label: "男", value: "1" },
              { label: "女", value: "2" },
            ],
            isEdit: false,
          },
          {
            id: 2,
            userName: "12",
            phoneNumber: "13554099888",
            email: "11@qq.com",
            genderType: "1",
            password: "1",
            birthday: "1",
            updateTime: "Y",
            genderTypeList: [
              { label: "男", value: "1" },
              { label: "女", value: "2" },
            ],
            isEdit: false,
          },
          {
            id: 3,
            userName: "13",
            phoneNumber: "13554099888",
            email: "11@qq.com",
            genderType: "1",
            password: "1",
            birthday: "1",
            updateTime: "Y",
            genderTypeList: [
              { label: "男", value: "1" },
              { label: "女", value: "2" },
            ],
            isEdit: false,
          },
          {
            id: 4,
            userName: "14",
            phoneNumber: "13554099888",
            email: "11@qq.com",
            genderType: "1",
            password: "1",
            birthday: "1",
            updateTime: "Y",
            genderTypeList: [
              { label: "男", value: "1" },
              { label: "女", value: "2" },
            ],
            isEdit: false,
          },
          {
            id: 4,
            userName: "15",
            phoneNumber: "13554099888",
            email: "11@qq.com",
            genderType: "1",
            password: "1",
            birthday: "1",
            updateTime: "Y",
            genderTypeList: [
              { label: "男", value: "1" },
              { label: "女", value: "2" },
            ],
            isEdit: false,
          },
          {
            id: 5,
            userName: "16",
            phoneNumber: "13554099888",
            email: "11@qq.com",
            genderType: "1",
            password: "1",
            birthday: "1",
            updateTime: "Y",
            genderTypeList: [
              { label: "男", value: "1" },
              { label: "女", value: "2" },
            ],
            isEdit: false,
          },
        ];
        let TableList = JSON.parse(localStorage.getItem("TableList"));
        console.log(TableList);
        this.model = TableList && TableList.length ? TableList : newData;
        this.tableId = this.model.length;
      },
      methods: {
        handleClick(row) {
          console.log(row);
        },
        submitForm(formName) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              this.dynamicValidateForm.birthday = getNowFormatDate(
                this.dynamicValidateForm.birthday
              );
              this.dynamicValidateForm.birthday = getNowFormatDate(
                this.dynamicValidateForm.birthday
              );
              this.dynamicValidateForm.updateTime = new Date().toLocaleString();
              let realInd = this.model.findIndex((el) => {
                return el.id === this.updateInd;
              });

              if (this.isUpdate && this.updateInd != null) {
                console.log(this.dynamicValidateForm);
                this.model[realInd].email = this.dynamicValidateForm.email;
                this.model[realInd].userName =
                  this.dynamicValidateForm.userName;
                this.model[realInd].phoneNumber =
                  this.dynamicValidateForm.phoneNumber;
                this.model[realInd].genderType =
                  this.dynamicValidateForm.genderType;
                this.model[realInd].password =
                  this.dynamicValidateForm.password;
                this.model[realInd].birthday =
                  this.dynamicValidateForm.birthday;
                this.model[realInd].updateTime =
                  this.dynamicValidateForm.updateTime;
                console.log(this.model[realInd]);
              } else {
                this.model.push(this.dynamicValidateForm);
              }
              this.dialogVisible = false;
              this.updateInd = null;
              this.isUpdate = false;
            } else {
              console.log("error submit!!");
              return false;
            }
          });
        },
        resetForm(formName) {
          this.$refs[formName].resetFields();
        },
        current_change: function (currentPage) {
          this.currentPage = currentPage;
        },
        deleteList(ind) {
          this.centerDialogVisible = true;
          this.deleteRow = ind;
        },
        cancelForm() {
          let index = this.model.findIndex((el) => {
            return el.id === this.deleteRow.row.id;
          });
          this.model.splice(index, 1);
          this.centerDialogVisible = false;
        },
        // 添加list
        addListItem(ind) {
          let j = {
            id: 0,
            type: "",
            isEdit: true,
            key: Date.now(),
            _temporary: true,
            userName: "",
            phoneNumber: "",
            email: "",
            genderType: "1",
            password: "",
            birthday: "",
            updateTime: "",
            genderTypeList: [
              { label: "男", value: "1" },
              { label: "女", value: "2" },
            ],
          };
          if (ind) {
            this.isUpdate = true;
            this.updateInd = ind.id;
            j.id = ind.id;
            j.birthday = ind.birthday;
            j.userName = ind.userName;
            j.phoneNumber = ind.phoneNumber;
            j.password = ind.password;
            j.genderType = ind.genderType;
            j.email = ind.email;
            j.updateTime = ind.updateTime;
            this.dynamicValidateForm = JSON.parse(JSON.stringify(j));
          } else {
            this.tableId++;
            j.id = this.tableId;
            this.dynamicValidateForm = j;
          }
          this.dialogVisible = true;
        },
      },
    });
  </script>
</html>

posted @ 2021-06-29 15:50  smartwange  阅读(51)  评论(0)    收藏  举报