需求背景
在Vue3環境中,動態增加或者刪除表格的行,該怎么實現?如下圖:
實現分析
不同于傳統js,jquery等框架的面向dom編程,vue中是面向數據編程。對變量的增刪自動綁定到dom節點的增刪上,所以在vue中動態增加或者刪除表格行無須編寫復雜的dom節點操作,直接對變量進行增刪操作即可。
解決辦法
定義一個列表變量,循環列表變量展示表格的行即可,通過對列表變量增加元素或者刪除元素實現綁定的表格行的增加或刪除。直接上代碼。
變量:
/**價格列表 */
const goodsPriceList = ref([]);
頁面:
<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>
函數:
/** 新增 */
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)}
}