• ElementUI table表格中 input select 校验 验证


    Element-UI table表格中 input select 校验 验证

    效果如图

    完整代码:

    例子一

    /**
    * @description: 添加设置成本价格
    */
    <template>
      <div>
        <el-row>
          <el-col :span="24">
            <el-form :model="SKUPriceList" ref="skuForm" size="small">
              <el-table v-if="SKUPriceList.data" size="mini"
                        :data="SKUPriceList.data" border
                        class="SKU-table"
                        style=" 100%"
                        highlight-current-row>
                <el-table-column type="index" label="序号" width="50">
                  <template slot-scope="scope">
                    <div style="margin-bottom: 18px;">{{scope.$index + 1}}</div>
                  </template>
                </el-table-column>
                <el-table-column v-for="(v,i) in SKUPriceList.columns"
                                 :key="'SKUPriceList' + i"
                                 :prop="v.field"
                                 :label="v.title"
                                 :width="v.width">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'data.' + scope.$index + '.'+v.field"
                      :rules="scope.row.isSet ? rules[v.field] : {}">
                      <span v-if="scope.row.isSet">
                          <template  v-if="v.field === 'supplierSysNo'">
                      <el-popover
                        trigger="click"
                        placement="bottom"
                        :visible-arrow="false"
                        popper-class="organization-popover"
                        :offset="0"
                        width="250">
                        <div>
                          <div class="flex-row justify-end">
                            <i class="el-icon-circle-close ft14" @click="handleClosePopover"></i>
                          </div>
                          <el-select
                          v-model="selectSupplierSysNo"
                          size="mini"
                          filterable
                          remote
                          reserve-keyword
                          style=" 220px"
                          :remote-method="remoteMethod"
                          :loading="loading"
                          @change="(val)=>selectChange(val, scope.row)"
                          placeholder="请选择">
                            <el-option
                              v-for="item in supplierDevice"
                              :key="item.supplierSysNo"
                              :label="item.supplierName"
                              :value="item.supplierSysNo">
                            </el-option>
                          </el-select>
                        </div>
    
                        <el-input v-model="scope.row.supplierName"
                                  readOnly
                                  size="mini"
                                  maxlength="20"
                                  style=" 250px"
                                  slot="reference"
                                  placeholder="请选择"></el-input>
                    </el-popover>
                    </template>
                           <el-input v-else
                               v-model="scope.row[v.field]"
                               size="mini"
                               maxlength="20"
                               placeholder="请输入内容"></el-input>
                  </span>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" size="small" style="margin-bottom: 18px;"
                               @click="() => SKUPriceList.data.splice(scope.$index, 1)">删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </el-col>
          <el-col :span="24">
            <div class="addsku" @click="addSKUPriceList">新增价格</div>
          </el-col>
        </el-row>
        <div class="flex-row center mt40">
          <el-button size="small" @click="() => $emit('update:showSKUSetting', false)">取 消</el-button>
          <el-button size="small" type="primary" @click="updateSKUList()">确认</el-button>
        </div>
      </div>
    
    </template>
    
    <script>
      import VueTypes from 'vue-types'
      //id生成工具
      const generateId = {
        _count: 1,
        get() {
          return ( ( +new Date() ) + '_' + ( this._count++ ) )
        }
      }
      export default {
        name: 'SetSupplierPriceList',
        props: {
          dataSource: VueTypes.array.def([]),
          listIndex: VueTypes.number.def(0),
          showSKUSetting: VueTypes.bool.def(false)
        },
        data() {
          const validatePrice = (_, value, callback) => {
            let reg = /(^[1-9]{1}[0-9]*$)|(^[0-9]*\.[0-9]{1,2}$)/
              if (String(value) === '0') {
                callback()
              } else {
                if (!value || !String(value).length) {
                  return callback(new Error('请输入成本价格'))
                } else if (!reg.test(value)) {
                  const errorStr = '请输入不小于0,两位小数以内的数字'
                  return callback(new Error(errorStr))
                }
                callback()
              }
          }
          return {
            loading: false,
            visible: false,
            selectSupplierSysNo: null,
            rules: {
              supplierSysNo: [
                { required: true, message: '请选择名称', trigger: 'change' }
              ],
              price: [
                { required: true, validator: validatePrice, trigger: 'blur'}
              ],
            },
            supplierDevice: [],
            list: [],
            states: ["Alabama", "Alaska", "Arizona",
            "Arkansas", "California", "Colorado",
            "Connecticut", "Delaware", "Florida",
            "Georgia", "Hawaii", "Idaho", "Illinois",
            "Indiana", "Iowa", "Kansas", "Kentucky",
            "Louisiana", "Maine", "Maryland",
            "Massachusetts", "Michigan", "Minnesota",
            "Mississippi", "Missouri", "Montana",
            "Nebraska", "Nevada", "New Hampshire",
            "New Jersey", "New Mexico", "New York",
            "North Carolina", "North Dakota", "Ohio",
            "Oklahoma", "Oregon", "Pennsylvania",
            "Rhode Island", "South Carolina",
            "South Dakota", "Tennessee", "Texas",
            "Utah", "Vermont", "Virginia",
            "Washington", "West Virginia", "Wisconsin",
            "Wyoming"]
          }
            SKUPriceList: {
              columns: [
                {field: 'supplierSysNo', title: '名称',  270},
                {field: 'price', title: '价格',  220},
              ],
              data: [],
            },
          }
        },
        mounted() {
          // 初始化数据
          if (this.dataSource && this.dataSource.length > 0) {
            this.SKUPriceList.data = this.dataSource.map(i => {
              return {
                id: generateId.get(),//模拟后台插入成功后有了id
                isSet: true,
                ...i
              }
            })
          }
         this.list = this.states.map((item, index) => {
            return { supplierSysNo: `value:${index}`, supplierName: `label:${item}` };
          });
        },
        methods: {
          handleClosePopover() {
            if (document.all) {
              document.getElementsById('app').click()
            } else {
              let e = document.createEvent('MouseEvents')
              e.initEvent('click', true, true)
              document.getElementById('app').dispatchEvent(e)
            }
            this.selectSupplierSysNo = null
          },
           remoteMethod(query) {
            if (query !== '') {
              this.loading = true;
              setTimeout(() => {
                this.loading = false;
                this.supplierDevice = this.list.filter(item => {
                  return item.supplierName.toLowerCase()
                    .indexOf(query.toLowerCase()) > -1;
                });
              }, 200);
            } else {
              this.supplierDevice = [];
            }
          }
        },
          selectChange(val, row) {
            this.selectSupplierSysNo = val
            row['supplierSysNo'] = val
            this.supplierDevice.forEach(item => {
              if (item.supplierSysNo === val) {
                row['supplierName'] = item.supplierName
              }
            })
          },
          //添加数据
          addSKUPriceList() {
            const j = {
              id: 0,
              supplierName: '',
              supplierSysNo: null,
              price: '',
              isSet: true,
              error: false
            }
            this.SKUPriceList.data.push(j)
          },
          updateSKUList() {
            if (this.SKUPriceList.data.length < 1) return this.$message.warning('请设置至少一条数据!')
            this.$refs['skuForm'].validate(valid => {
              if (valid) {
                this.$emit('updateSupplierPriceList', this.SKUPriceList.data, this.listIndex)
              } else {
                console.log('error submit!!')
                return false
              }
            })
          }
        }
      }
    </script>
    
    <style lang="less" rel="stylesheet/less">
    </style>
    
    

    例子二

    <!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()" size="mini"
            >添加</el-button
          >
          <el-button type="success" @click="saveList('form')" size="mini">保存</el-button>
          <el-form :model="model" ref="form" size="small">
            <el-table :data="model.list" style=" 100%;" row-key="key">
              <el-table-column
                v-for="item in tableHeadData"
                :key="item.key"
                :label="item.label"
                :width="item.width"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'list.' + scope.$index + '.'+item.name"
                    :rules="scope.row.isEdit ? rules[item.name] : {}"
                  >
                    <!-- 判断是展示列表还是新增 
                    判断编辑状态下是input还是select -->
                    <span v-if="!scope.row.isEdit && isSelect.indexOf(item.name) < 0">{{ scope.row[item.name] }}</span>
                    <el-input
                      v-model="scope.row[item.name]"
                      v-if="scope.row.isEdit && isSelect.indexOf(item.name) < 0"
                    ></el-input>
                    <el-select
                      v-model="scope.row[item.name]"
                      v-if="isSelect.indexOf(item.name) > -1"
                      :disabled="!scope.row.isEdit"
                    >
                      <el-option
                        v-for="childItem in scope.row[item.name+'List']"
                        :key="childItem.value"
                        :label="childItem.label"
                        :value="childItem.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
            <!-- </el-form-item> -->
          </el-form>
        </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>
        new Vue({
          el: '#app',
          data: function() {
            // 可以把校验规则单独提出一个js文件 通过export方式导
            // 写在这里是为了此篇博客的展示
            var validatePass = (rule, value, callback) => {
              console.log(rule, value)
              if (value === '') {
                callback(new Error('请输入Warehouse'))
              }
              if (value) {
                // 用写死value的方式 模拟接口请求
                if (value == '345') {
                  callback(new Error('Warehouse已经存在'))
                } else {
                  callback()
                }
              }
            }
            return {
              // list数据
              model: {
                list: []
              },
              newModel: [],
              // 表头字段
              tableHeadData: [
                {
                  name: 'warehouse',
                   160,
                  label: 'Warehouse'
                },
                {
                  name: 'description',
                   160,
                  label: 'Description'
                },
                {
                  name: 'warehouseType',
                   160,
                  label: 'Warehouse Type'
                },
                {
                  name: 'extWarehouse',
                   160,
                  label: 'Ext Warehouse'
                },
                {
                  name: 'goodsReceiptStep',
                   160,
                  label: 'Goods Receipt Step'
                },
                {
                  name: 'goodsIssueStep',
                   160,
                  label: 'Goods Issue Step'
                },
                {
                  name: 'pickingStrategy',
                   160,
                  label: 'Picking Strategy'
                },
                {
                  name: 'email',
                   210,
                  label: 'Email'
                },
              ],
              // 下拉选项判断条件
              isSelect: ['warehouseType', 'goodsReceiptStep', 'pickingStrategy'],
              // 校验规则
              rules: {
                warehouse: [{ validator: validatePass, trigger: 'blur' }],
                description: [
                  { required: true, message: '请输入description', trigger: 'blur'}
                ],
                warehouseType: [
                  { required: true, message: '请选择', trigger: 'change' }
                ],
                // 非必填但是填了就要复合email的格式
                email: [
                  { type: 'email', message: '请输入正确的Emall', trigger: 'blur' }
                ]
              }
            }
          },
          mounted() {
            // 模拟接口请求赋值
            this.model.list = [{
              warehouse: '345',
              description: '345',
              warehouseType: '1',
              extWarehouse: '1',
              goodsReceiptStep: '1',
              goodsIssueStep: '1',
              pickingStrategy: 'Y',
              email: 'guozongzhang1@163.com',
              warehouseTypeList: [
                { label: '内部仓库', value: '1' },
                { label: '外部仓库', value: '2' }
              ],
              goodsReceiptStepList: [
                { label: '一步', value: '1' },
                { label: '二步', value: '2' }
              ],
              pickingStrategyList: [
                { label: '跳过pick', value: 'Y' },
                { label: '不跳过pick', value: 'N' }
              ]
            }]
          },
          methods: {
            // 添加list
            addListItem() {
              let addItem = {}
              this.tableHeadData.forEach(item => {
                addItem[item.name] = ''
                addItem['isEdit'] = true
                addItem.key = Date.now()
                addItem['warehouseTypeList'] = [
                  { label: '内部仓库', value: '1' },
                  { label: '外部仓库', value: '2' }
                ]
                addItem['goodsReceiptStepList'] = [
                  { label: '一步', value: '1' },
                  { label: '二步', value: '2' }
                ]
                addItem['pickingStrategyList'] = [
                  { label: '跳过pick', value: 'Y' },
                  { label: '不跳过pick', value: 'N' }
                ]
              })
              this.model.list.unshift(addItem)
            },
            // 保存
            saveList(formName) {
              this.$refs[formName].validate(valid => {
                if (valid) {
                  console.log('success')
                } else {
                  console.log('error submit!!')
                  return false
                }
              })
    
            }
          }
        })
      </script>
    </html>
    
  • 相关阅读:
    正睿提高组2017模拟题三T1
    数位dp【转载】
    正睿提高组2017模拟题二T2
    【树状数组二维区间加+区间查询模板】bzoj3132
    【树状数组区间加+区间查询模板】洛谷P3372
    51Nod
    CodeForces 631E Product Sum
    CodeForces
    [不知道哪来的题] 完美理论
    CodeForces
  • 原文地址:https://www.cnblogs.com/CandyDChen/p/16330531.html
Copyright © 2020-2023  润新知