restartItemId(ids) {
let idList = ids
const loading = this.$loading({
lock: true,
text: '正在重启',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)',
})
if (idList.length === 0) {
// debugger
this.getItems()
loading.close()
// debugger
this.$message({ message: '重启成功', type: 'success' })
return
} else {
let val = idList.shift()
this.$http.postJSON('/sm/reboot/', { server_ids: [val] }).then(res => {
if (res.data.code === 200) {
this.restartItemId(idList)
} else {
loading.close()
this.$message({ message: res.data.message, type: 'warning' })
}
})
}
},
restartItem() {
if (this.multipleSelection.length == 0) {
this.$message({ message: '请勾选数据', type: 'warning' })
} else {
let ids = []
this.multipleSelection.map(item => {
ids.push(item.id)
})
// this.restartItemId(ids)
this.$confirm('确认是否重启?', '确认', {
type: 'warning',
})
.then(() => {
this.restartItemId(ids)
})
.catch(() => {
this.$refs.table.clearSelection()
})
}
},
解决思路:vue项目中要实现批量操作,如批量增删改查,主要通过利用穿不同的参数调用同一个接口,然后实现批量操作的,可以通过递归来实现。
以批量重启为例
1.将判断是否有选中,如果没有,提示用户进行选择,如果有进行下步操作
2.确认是否进行批量操作,如果取消,则取消用户的选择,如果确认,则调用实现递归的函数 this.restartItemId(ids)
3.调用函数 this.restartItemId(ids)需要将用户选中的id放在一个方法里面,然后以参数的形式传递过去
4.点击重启后,因为重启稍微有点慢,所以打开遮盖层(防止用户操作,并且这时的操作没有效果,因为需要等待重启的接口调完之后,才能调用其它接口)显示正在重启。
5.进入if判断,因为刚传过来的ids数组肯定不为空,所以进入else里面的内容
6.通过shift方法拿到ids数组的第一个值(同样也会影响原数组,即原数组第一个值会被删除,),然后调用接口,如果调用失败,则取消遮盖层,显示重启失败的信息。
7.接口调用成功后,再次调用his.restartItemId(idList),注释:如果直接将ids传过去,重新调用his.restartItemId()这个方法,ids还是原来的,不会因为shift方法影响ids(因为是重新从restartItem()函数传过来的,所以是新的ids),所以之前要定义一个变量idList来接收传过来的参数ids,这样用idList.shift()方法,idList会在每一次执行调用接口后,都会使idList少一个值。
8.再次调用his.restartItemId(idList),判断idList是否为空,如果不为空,继续执行以上逻辑,如果为空,则刷新数据,关闭遮盖层,显示重启成功的信息,return 空,则会跳出递归。