elment UI 表格 item 驗證問題解決方案

需求背景

各位大拿,不知道大家在平時工做中有沒有遇到要在明細表格中又有各類操做以及規格驗證的需求,以下圖:javascript

效果以下:java

難點

由於表格是可添加行的,而每條數據對應的字段在表格中是同樣的,而後在作表單驗證的時候數據的key必需要惟一的,並且得是對象,這兩個數據的數據格式是不一樣的,我是這樣想的,只要解決了映射關係,問題就能解決了。因此想出了下面的方法bash

解決方案

項目採用 Vue + Element UI 開發: 我目前採用的方案是在 el-table 外加了一層 el-form,而後聲明 tableForm 來綁定表單數據,包括作一些表單驗證, 聲明 tableData 表示表格數據,用來作合計以及數據初始化等渲染, template 代碼以下:ui

<el-form :rules="rules" :model="tableForm" ref='tableForm' size="small">
    <div class='btn-row'>
        <el-button type='primary' size="mini" @click="addRow">添加一行</el-button> 
        <el-button size="mini" @click="deleteRow">刪除</el-button>
    </div>
    <el-table :data="tableData" show-summary @selection-change="handleSelectionChange" ref="table" :summary-method="getSummaries">
        <el-table-column
          prop="startDate"
          label="出發日期"
          min-width="160px"
        >
            <template slot-scope="scope">
                <el-form-item :prop='"startDate" + scope.row.id' :rules="rules.startDate" class="form-item__margin">
                  <el-date-picker
                    v-model="tableForm['startDate' + scope.row.id]"
                    @input="changeValue('startDate', scope.$index, scope.row.id)"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="選擇日期"
                  >
                  </el-date-picker>
                </el-form-item>
            </template>
        </el-table-column>
    </el-table>
</el-form>
複製代碼

由於表單是能夠添加行以及刪除行的,並且操做並不在每一行中,因此這裏須要有個標識,而後數據裏面並無可用的 id, 因此這裏我作了如下操做:this

// 初始化
init () {
  const id = +moment()
  const data = {...this.initData}
  for (let [key, value] of Object.entries(this.initData)) {
    this.$set(this.tableForm, `${key}${id}`, value)
  }
  data.id = id
  this.tableData.push(data)
}
複製代碼

初始化的操做ok了 主要是加上了 id 以及將初始化字段展開平鋪到 tableForm 對象中去,添加行的方法其實和 init 同樣,就是作一個添加標識符以及展開操做,刪除操做有些不同,但也很簡單spa

// 刪除選中行
deleteRow () {
  const {checkedRow, tableData} = this
  if (!checkedRow.length) {
    this.$message({
      message: `沒有選中項`,
      type: 'warning'
    })
    return
  }
  const ids = []
  checkedRow.forEach(item => {
    ids.push(item.id)
  })
  const newTable = tableData.filter(item => {
    return !ids.includes(item.id)
  })
  this.tableData = newTable
  for (let [key, value] of Object.entries(this.tableForm)) {
    for (let id of ids) {
      if (key.includes(id)) {
        delete this.tableForm[key]
      }
    }
  }
},
複製代碼

注意在模板裏的寫法,code

`<el-form-item :prop='"startDate" + scope.row.id' :rules="rules.startDate"> ...`
以及
`<component v-model="tableForm['startDate' + scope.row.id]"  @input="changeValue('startDate', scope.$index, scope.row.id)"> ...`
複製代碼

結語

好了,目前算是已經解決這個需求了,不知道有沒有小夥伴有更好的方案,歡迎賜教。component

相關文章
相關標籤/搜索