1. 程式人生 > 其它 >Element-UI table表格中 input select 校驗 驗證

Element-UI 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="width: 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="width: 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="width: 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: '名稱', width: 270},
            {field: 'price', title: '價格', width: 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="width: 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',
              width: 160,
              label: 'Warehouse'
            },
            {
              name: 'description',
              width: 160,
              label: 'Description'
            },
            {
              name: 'warehouseType',
              width: 160,
              label: 'Warehouse Type'
            },
            {
              name: 'extWarehouse',
              width: 160,
              label: 'Ext Warehouse'
            },
            {
              name: 'goodsReceiptStep',
              width: 160,
              label: 'Goods Receipt Step'
            },
            {
              name: 'goodsIssueStep',
              width: 160,
              label: 'Goods Issue Step'
            },
            {
              name: 'pickingStrategy',
              width: 160,
              label: 'Picking Strategy'
            },
            {
              name: 'email',
              width: 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: '[email protected]',
          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>