下面給大家介紹一下前端的刪除方法,在開發(fā)中 我們常常會碰到這種業(yè)務(wù),有一些數(shù)據(jù)需要在前端進(jìn)行刪除,我們并不希望他走后端的接口,而是在點擊提交或者其他的業(yè)務(wù)完成后才走接口,這時我們就用到了vue的前端刪除方法。
首先給大家介紹一下刪除一條數(shù)據(jù)的情況:
在element ui的el-table 我們需要先寫出刪除按鈕
<el-table
ref="departmentTable"
:data="tableDepartmentList.data"
style="width: 100%"
@selection-change="handleSelectionChangeDepartment"
>
<el-table-column label="操作" width="70">
<template slot-scope="scope">
<span style="cursor: pointer" @click="deleteDepartmentRow(scope.$index)">
<i class="el-icon-delete"></i>
</span>
</template>
</el-table-column>
</el-table>
<!-- scope.$index 就是你刪除的數(shù)據(jù)在第幾行,第一行就返回1,以此類推。把這個參數(shù)傳入用于刪除 -->
接下來就可以在methods 中定義出這個方法了
methods: {
deleteDepartmentRow(index) {
this.$confirm("此操作將刪除信息, 是否繼續(xù)?", "提示", {
confirmButtonText: "確定",
cancelButtonText: "取消",
type: "warning"
})
.then(() => {
this.tableDepartmentList.data.splice(index, 1);
this.$message({
type: "success",
message: "刪除成功!"
});
})
.catch(() => {
this.$message({
type: "info",
message: "已取消刪除"
});
});
}
// 第九行代碼就是執(zhí)行的刪除方法,this.tableDepartmentList.data,是el-table綁定的數(shù)據(jù),不多解釋。splice()方法中可以傳入1-3個
// 參數(shù),這里只介紹倆參數(shù)的 其他的大家可以去查一下,很簡單。
// 當(dāng)splice(index, 1)中傳入兩個參數(shù)的意思就是: index就是剛剛我們傳入的行數(shù),就是刪除剛剛我們選中那行的數(shù)據(jù). 1代表刪除一條
批量刪除:
批量刪除我們需要配合el-table中的 selection來使用,也就是下面的第七行
<el-table
ref="departmentTable"
:data="tableDepartmentList.data."
style="width: 100%"
@selection-change="handleSelectionChangeDepartment"
>
<el-table-column type="selection" width="55"></el-table-column>
<el-table-column label="操作" width="70">
<template slot-scope="scope">
<span style="cursor: pointer" @click="deleteDepartmentRow(scope.$index, scope.row)">
<i class="el-icon-delete"></i>
</span>
</template>
</el-table-column>
</el-table>
<el-button @click="deleteSelected()">批量刪除</el-button>
首先需要注意的是 @selection-change=“handleSelectionChangeDepartment”文章來源:http://www.zghlxwxcb.cn/news/detail-517215.html
@selection-change 是組件當(dāng)中自帶的一個方法,它可以取到我們選擇的行的值,所以我們在data中定義一個數(shù)組,用于保存這些值,官方組件中有解釋,大家可以去看看文章來源地址http://www.zghlxwxcb.cn/news/detail-517215.html
data() {
return {
multipleSelectionDepartment: [],
}
},
methods: {
// 用于保存選中的行
handleSelectionChangeDepartment(val) {
this.multipleSelectionDepartment = val;
},
deleteSelected(){
this.$confirm('此操作將批量刪除部門, 是否繼續(xù)?', '提示', {
confirmButtonText: '確定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
let val = this.multipleSelectionDepartment //選中的值
if (val) {
val.forEach((val, index) => { // 這塊看不明白的話看下面的解釋
this.tableDepartmentList.data.forEach((v, i) => {
if (val.deptName === v.deptName) {
this.tableDepartmentList.data.splice(i, 1)
}
})
})
}
this.$message.success("刪除成功")
})
},
}
// 第一層循環(huán)就是循環(huán)我們選中的值,第二層循環(huán)就是循環(huán)我們this.tableDepartmentList.data 中所有的值,然后去判斷,
// 如果有一樣的數(shù)據(jù)的話就進(jìn)行刪除
到了這里,關(guān)于VUE前端刪除和批量刪除的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!