首先: filter方法的使用可以参考: https://blog.csdn.net/weixin_41615439/article/details/108661807
使用filter操作对象数组,可以减少不必要的请求;如果不是对象数组,那filter方法是没有改变原数组的。
1、首先,表格数据我已经拿到
2、点击删除,逻辑代码如下:
// 删除表格某个数据
del(id) {
// 判断是多选还是单选
let delType = id instanceof Array
let length = 0
let changeId = ''
if(delType) {
// 多条
length = id.length
// 数组转字符串
changeId = id.join(',')
} else {
changeId = id
}
this.$confirm({
title: delType? `您确定要删除这${length}个站点吗?`: '您确定要删除该站点吗?',
content: '删除后不可恢复哦',
okText: '确定',
okType: 'danger',
cancelText: '取消',
onOk() {
// 调用删除接口
delData(changeId)
.then(res => {
if(res.data.code === 0) {
// 删除成功更新数据
if(delType) {
// 如果是多选,遍历id数组
id.forEach(item => {
// 通过选中的id与原对象数组的id判断,不相同则留着
this.tableData = this.tableData.filter(it => it.id != item)
})
} else {
// 单选则直接把选中的id和原对象数组的id比较
this.tableData = this.tableData.filter(it => it.id != changeId)
}
}
})
},
onCancel() {
// 关闭提示
},
});
},
3、运行后保错:
4、修改的代码:
// 删除表格某个数据
del(id) {
// 解决报未定义的错
let that = this
// 判断是多选还是单选
let delType = id instanceof Array
let length = 0
let changeId = ''
if(delType) {
// 多条
length = id.length
// 数组转字符串
changeId = id.join(',')
} else {
changeId = id
}
that.$confirm({
title: delType? `您确定要删除这${length}个站点吗?`: '您确定要删除该站点吗?',
content: '删除后不可恢复哦',
okText: '确定',
okType: 'danger',
cancelText: '取消',
onOk() {
// 调用删除接口
delData(changeId)
.then(res => {
if(res.data.code === 0) {
// 删除成功更新数据
if(delType) {
// 如果是多选,遍历id数组
id.forEach(item => {
// 通过选中的id与原对象数组的id判断,不相同则留着
that.tableData = that.tableData.filter(it => it.id != item)
})
} else {
// 单选则直接把选中的id和原对象数组的id比较
that.tableData = that.tableData.filter(it => it.id != changeId)
}
}
})
},
onCancel() {
// 关闭提示
},
});
},
主要是增加了
let that = this
只因热爱,愿迎万难