开发避坑指南(30):Vue3 表格动态增加删除行解决方案

需求背景

在Vue3环境中,动态增加或者删除表格的行,该怎么实现?如下图:

实现分析

不同于传统js,jquery等框架的面向dom编程,vue中是面向数据编程。对变量的增删自动绑定到dom节点的增删上,所以在vue中动态增加或者删除表格行无须编写复杂的dom节点操作,直接对变量进行增删操作即可。

解决办法

定义一个列表变量,循环列表变量展示表格的行即可,通过对列表变量增加元素或者删除元素实现绑定的表格行的增加或删除。直接上代码。

变量:

vue 复制代码
/**价格列表 */
const goodsPriceList = ref([]);

页面:

vue 复制代码
<el-row type="flex" justify="center" :gutter="15">
  <el-col :span="8">
    <h4 class="text-center">数量</h4>
  </el-col>
  <el-col :span="8">
    <h4 class="text-center">单价</h4>
  </el-col>
  <el-col :span="8">
    <h4 class="text-center">操作</h4>
  </el-col>              
</el-row>

<div v-for="(item, index) in goodsPriceList" :key="index + 100">
  <el-row type="flex" justify="center" :gutter="15">
    <el-col :span="8" class="text-center">
      <el-form-item :prop="'goodsPriceList.' + index + '.count'">
        <el-input v-model="item.count" placeholder="请输入商品数量" />
      </el-form-item>
    </el-col>
    <el-col :span="8" class="text-center">
      <el-form-item :prop="'goodsPriceList.' + index + '.price'">
        <el-input v-model="item.price" placeholder="请输入单价" />
      </el-form-item>
    </el-col>     
    <el-col :span="8" class="text-center">
      <el-button plain icon="Plus" type="primary" @click="handleAddGoodsPrice" v-if="index == goodsPriceList.length-1">新增</el-button>
      <el-button plain icon="Delete" type="danger" @click="handleRemoveGoodsPrice(index)">删除</el-button>
    </el-col>           
  </el-row>
</div>           

函数:

javascript 复制代码
/** 新增 */
function handleAddGoodsPrice() {
  let newGoodsPrice = {
      count:'',
      price:''
  }
  goodsPriceList.value.push(newGoodsPrice);  
}

/** 删除 */
function handleRemoveGoodsPrice(index) {
  if (index >= 0 && index < goodsPriceList.value.length) {
    goodsPriceList.value.splice(index, 1)
  }
}