封装el-table为可编辑表格

在这里插入图片描述

代码

<template>
  <div class="edit-table">
    <el-button
      ref="button"
      type="primary"
      size="medium"
      @click.native.prevent="handleAddRow"
    >
      <i class="el-icon-plus"></i>
      添加
    </el-button>
    <el-form :rules="rules" :model="form" ref="ruleForm">
      <el-table
        id="dialog-table"
        :data="form.tableData"
        size="small"
        class="table-wrap"
        @cell-mouse-enter="handleCellEnter"
        @cell-mouse-leave="handleCellLeave"
        @cell-click="handleCellClick"
      >
        <el-table-column prop="categoryValue" label="码表值" width="300">
          <template slot-scope="scope">
            <el-form-item
              :prop="'tableData.' + scope.$index + '.categoryValue'"
              :rules="rules.categoryValue"
            >
              <el-input
                ref="categoryValueInput"
                class="item__input"
                v-model="scope.row.categoryValue"
                placeholder="请输入内容"
                @blur="handleSaveRow(scope.row)"
                maxlength="50"
                show-word-limit
              ></el-input>
            </el-form-item>
            <div ref="categoryValueTxt" class="item__txt l-box-start-center">
              {{ scope.row.categoryValue }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="categoryKey" label="码表项" width="300">
          <div class="item" slot-scope="scope">
            <el-form-item
              :prop="'tableData.' + scope.$index + '.categoryKey'"
              :rules="rules.categoryKey"
            >
              <el-input
                ref="categoryKeyInput"
                class="item__input"
                v-model="scope.row.categoryKey"
                placeholder="请输入内容"
                @blur="handleSaveRow(scope.row)"
                maxlength="50"
                show-word-limit
              ></el-input>
            </el-form-item>
            <div ref="categoryKeyTxt" class="item__txt l-box-start-center">
              {{ scope.row.categoryKey }}
            </div>
          </div>
        </el-table-column>
        <el-table-column prop="notValid" label="有效标识">
          <div class="item" slot-scope="scope">
            <el-select
              class="item__input select__input l-box-start-center"
              popper-class="edittable-select"
              v-model="scope.row.notValid"
              placeholder="请选择"
              @blur="handleSaveRow(scope.row)"
            >
              <el-option
                v-for="item in validOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <div class="item__txt l-box-start-center">
              {{ validLabel(scope.row.notValid) }}
            </div>
          </div>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              class="edit-table-btn-oper"
              @click.native.prevent="handleDeleteRow(scope.$index, scope.row)"
              type="text"
              size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'EditTable',
  props: {
    categoryList: {
      type: Array,
      default: () => [],
    },
    isEditMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 下拉选项
      validOptions: [
        {
          value: '00',
          label: '有效',
        },
        {
          value: '01',
          label: '无效',
        },
      ],
      // 需要编辑的属性
      editProp: ['categoryKey', 'categoryValue', 'notValid'],
      clickCellMap: {}, // 记录当前编辑行所有cell的id,用于失焦时取消编辑状态
      changeCnt: 0,
      form: {
        tableData: _.cloneDeep(this.categoryList),
      },
      rules: {
        categoryValue: [
          {
            required: true,
            message: '码表值不能为空',
            trigger: 'blur',
          },
        ],
        categoryKey: [
          {
            required: true,
            message: '码表项不能为空',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  computed: {
    validLabel() {
      return (val) => {
        if (!val) {
          return '有效'
        }
        return this.validOptions.find((o) => o.value === val).label
      }
    },
  },
  created() {
    // this.init()
  },
  methods: {
    init() {
      // this.$nextTick(() => {
      //   console.log(this.form.tableData)
      // })
    },
    /** 鼠标移入cell */
    handleCellEnter(row, column, cell, event) {
      const property = column.property
      if (this.editProp.includes(property)) {
        cell.querySelector('.item__txt').classList.add('item__txt--hover')
      }
    },
    /** 鼠标移出cell */
    handleCellLeave(row, column, cell, event) {
      const property = column.property
      if (this.editProp.includes(property)) {
        cell.querySelector('.item__txt').classList.remove('item__txt--hover')
      }
    },
    /** 鼠标点击cell */
    handleCellClick(row, column, cell, event) {
      const property = column.property
      if (this.editProp.includes(property)) {
        // 保存cell
        this.saveCellClick(row, cell)
        this.setEditable(cell)
        // 下拉选框点击展开
        let selectCell = cell.querySelector('.item__input.select__input')
        selectCell && selectCell.__vue__.toggleMenu()
      }
    },
    /** 保存数据(失焦时触发) */
    handleSaveRow(curRow) {
      this.$refs.ruleForm.validate((valid, notValidObj) => {
        // 根据校验情况设置按钮状态
        this.$emit('setBtnDisabled', !valid)
        // 若当前行通过校验,则取消编辑状态
        const notValidRowIdx = Object.keys(notValidObj).map(
          (key) => key.match(/tableData\.(\S*)\.category/)[1]
        )
        const curRowValid = !notValidRowIdx.some(
          (idx) => idx == curRow.id.replace('row', '')
        )
        curRowValid && this.deleteCellClick(curRow.id)
      })
    },
    /** 保存进入编辑的cell */
    saveCellClick(row, cell) {
      const id = row.id
      if (this.clickCellMap[id] == undefined) {
        this.clickCellMap[id] = [cell]
        return
      }
      if (!this.clickCellMap[id].includes(cell)) {
        this.clickCellMap[id].push(cell)
      }
    },
    /** 删除取消编辑状态的cell */
    deleteCellClick(rowId) {
      // 取消当前行所有cell的编辑状态
      if (this.clickCellMap[rowId]) {
        this.clickCellMap[rowId].forEach((cell) => {
          this.cancelEditable(cell)
        })
        delete this.clickCellMap[rowId]
      }
    },
    /** 添加数据(点击添加触发) */
    handleAddRow() {
      const lastItemIndex = this.form.tableData.length
      const item = {
        id: `row${lastItemIndex}`, // 初始化,保存到后台会自动生成id
        categoryKey: '',
        categoryValue: '',
        notValid: '00',
      }
      this.form.tableData.push(item)
      this.$nextTick(() => {
        // 记录编辑状态
        const tableDom = document.getElementById('dialog-table')
        const rowDomList = tableDom.getElementsByClassName('el-table__row')
        const cell = rowDomList[lastItemIndex].querySelector('td')
        this.saveCellClick(item, cell)
        // 聚焦
        this.$refs.categoryValueTxt.style.display = 'none'
        this.$refs.categoryValueInput.$el.style.display = 'flex'
        this.$refs.categoryValueInput.$refs.input.focus()
      })
    },
    /** 删除数据(点击删除触发) */
    handleDeleteRow(index, row) {
      this.form.tableData.splice(index, 1)
      this.deleteCellClick(row.id)
      // 待界面更新后再进行验证
      this.$nextTick(() => {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) return
          // 列表不为空时, 确定按钮设为可用
          !_.isEmpty(this.categoryList) && this.$emit('setBtnDisabled', false)
        })
      })
    },
    /** 进入编辑状态 */
    setEditable(cell) {
      cell.querySelector('.item__txt').style.display = 'none'
      cell.querySelector('.item__input').style.display = 'flex'
      cell.querySelector('input').focus()
    },
    /** 取消编辑状态 */
    cancelEditable(cell) {
      cell.querySelector('.item__txt').style.display = 'flex'
      cell.querySelector('.item__input').style.display = 'none'
    },
    // moveToErr() {
    //   this.$nextTick(() => {
    //     let isError = document.getElementsByClassName('is-error')
    //     if (isError.length) {
    //       isError[0].scrollIntoView({
    //         block: 'center',
    //         behavior: 'smooth',
    //       })
    //       // 这个当滑动到报错项之后自动获取输入框的焦点,方便用户直接进行输入,延迟 800ms 是因为需要都能到定位成功后在进行获取焦点体验更好一些
    //       setTimeout(() => {
    //         if (isError[0]?.querySelector('input')) {
    //           isError[0].querySelector('input').focus()
    //         }
    //       }, 800)
    //     }
    //   })
    // },
  },
  watch: {
    // 监听表单变动更新状态
    'form.tableData': {
      handler(val) {
        // this.changeCnt++
        // if (
        //   // 编辑模式下第一次赋值不触发变动
        //   (!this.isEditMode && this.changeCnt > 0) ||
        //   (this.isEditMode && this.changeCnt > 1)
        // ) {
        //   this.$emit('updateCategoryList', _.cloneDeep(val))
        // }
        this.$emit('updateCategoryList', _.cloneDeep(val))
      },
      deep: true,
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .el-input__inner {
  padding-left: 8px;
}

.edit-table {
  height: 100%;
  overflow-y: auto;

  &-btn-oper {
    color: #358df6;
    font-weight: bold;
    font-size: 14px;
  }

  .table-wrap {
    width: 100%;
    height: calc(100% - 36px);
    overflow-y: auto;
  }

  .el-form-item {
    padding: 0;
    &.is-error {
      padding: 0 0 16px 0;
      .item__input {
        display: block !important;
      }

      & + .item__txt {
        display: none !important ;
      }
    }
  }
}
</style>

<style lang="less">
.el-table thead,
.el-table__row {
  color: #333333;
  font-size: 14px;
}

.item__input {
  display: none;
  /* 调整elementUI中样式 如果不需要调整请忽略 */
  .el-input__inner {
    height: 32px !important;
  }
  /* 调整elementUI中样式 如果不需要调整请忽略 */
  .el-input__suffix {
    i {
      font-size: 12px !important;
      line-height: 26px !important;
    }
  }
}
.item__txt {
  box-sizing: border-box;
  border: 1px solid transparent;
  width: 100%;
  height: 32px;
  line-height: 24px;
  padding: 0 8px;
}
.item__txt--hover {
  border: 1px solid #dddddd;
  border-radius: 4px;
  cursor: text;
}
.edittable-select {
  min-width: 311px !important;
}

.edit-table .el-table__body-wrapper {
  height: calc(100% - 40px);
  overflow-y: scroll;
}
</style>


可编辑表格未通过校验时,父组件不可提交表单

提交按钮设置disabled,校验通过才为true

未通过时,input框为可编辑状态;用样式改

    &.is-error {
      padding: 0 0 16px 0;
      .item__input {
        display: block !important;
      }

      & + .item__txt {
        display: none !important ;
      }
    }

问题:父组件从后台拿值后传给子组件,当子组件的数据依赖该值时,无法正常更新数据

注:直接用prop的值,数据更新正常

例:子组件中,某个数据依赖父组件发送请求传回的值

 <el-form :model="form" ref="ruleForm">
   <el-table
     id="dialog-table"
     :data="form.tableData"
     size="small"
     class="table-wrap"
   >
   ...
   </el-table>
 </el-form>
      
export default {
  props: {
    list: {
      type: Array,
      default: () => [],
    }
  },
  data() {
    return {
      form: {
        tableData: this.list,
      }
    }
  }

解决:父组件中,可利用 v-if 条件判断,在数据拿回来后,再渲染子组件
(可加上loading防止出现组件区域空白问题)

<div
  v-loading="!ruleForm.codeTableCategoryList.length"
>
  <div v-if="ruleForm.codeTableCategoryList.length">
    <comp :refer="ref" :basic="basic" :list="ruleForm.codeTableCategoryList" />
  </div>
</div>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Vue3封装el-table可以通过以下步骤进行: 1. 首先,我们需要创建一个自定义组件,可以命名为MyTable。 2. 在MyTable组件,我们需要导入el-tableel-table-column组件,可以使用import语句进行导入。 3. 在template标签,我们可以使用el-table来渲染表格。可以设置属性如:data、border、stripe等。 4. 在el-table标签内部,我们可以使用el-table-column来定义表格的列。可以设置属性如:prop(对应数据源)、label(列名)、width(列宽)等。 5. 在script标签,我们需要定义MyTable组件的props,用于接收父组件传递的数据。 6. 在script标签,我们可以定义一些方法或者计算属性,用于处理表格的点击事件、排序、筛选等。 7. 最后,我们需要在父组件使用MyTable组件,并传递数据和配置选项给MyTable组件的props,来渲染自定义的表格。 总结一下,Vue3封装el-table的关键步骤包括创建自定义组件、导入el-tableel-table-column组件、在MyTable组件使用el-tableel-table-column来渲染表格、定义props、定义方法和计算属性以及在父组件使用MyTable组件。通过封装el-table,我们可以更好地复用和管理表格组件,并实现更灵活的表格功能。 ### 回答2: Vue3是一个用于构建用户界面的渐进式JavaScript框架。它具有轻量级、高效、易用的特点,并且在Vue3可以灵活地封装el-table。 首先,为了封装el-table,我们可以创建一个自定义组件,命名为TableWrapper。在TableWrapper组件的模板使用el-table,并将el-table的相关属性、事件和插槽通过props进行传递和接收。 在TableWrapper组件的props,我们可以定义例如data、columns、pagination等与el-table相关的属性。这样,我们就可以通过在使用TableWrapper组件时传递这些属性来配置el-table的行为。 另外,我们还可以在TableWrapper组件定义一些需要自定义的功能,例如表格的样式、表头的固定、排序功能等。这些功能可以通过在TableWrapper组件添加相关的方法和事件来实现。 除了属性和方法外,我们还可以使用插槽在TableWrapper组件自定义表格的各个部分,例如表头、表尾、表格内容等。通过在TableWrapper组件的模板使用<slot>元素,并在使用TableWrapper组件时传递相应的内容,可以方便地自定义el-table的外观和布局。 总之,通过将el-table封装到自定义组件TableWrapper,我们可以更好地控制和定制el-table的行为和外观。这样,我们就能够根据实际需要快速构建出符合需求的数据表格。 ### 回答3: Vue3封装el-table的步骤如下: 1. 首先,创建一个名为el-table-wrapper的组件,该组件用于封装el-table。 2. 在el-table-wrapper组件,引入el-table组件,并在模板使用el-table进行数据展示。 3. 在el-table-wrapper组件,接收名为data的props属性,用于传递表格数据。 4. 在el-table-wrapper组件,通过v-for指令遍历data数据,并使用el-table-column组件进行表格列的定义。 5. 在el-table-wrapper组件,使用slot插槽来支持自定义表格内容,例如添加操作按钮等。 6. 在el-table-wrapper组件,可以设置一些其他属性,如border、stripe等,以适应不同的需求。 7. 在el-table-wrapper组件,可以使用事件监听器来捕获el-table的一些事件,例如选择行、排序等。 8. 在el-table-wrapper组件,通过emit方法触发自定义事件,以便在父组件处理表格的交互逻辑。 总结:在Vue3封装el-table,需要通过创建一个包装组件,在其引入el-table组件并定义相应的列和属性,同时支持自定义内容和事件。这样可以提高代码的复用性和可维护性,方便在不同的项目使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值