业务场景:左侧为笔记列表,右侧为某笔记详情。滚动加载列表,删除非第一页的笔记后,刷新笔记列表,并定位到删除笔记的位置。
data () {
return {
condition: {
page: 1,
pagesize: 10
},
list:[],
nowInfo:{},
nowIndex: 0, // 当前选中笔记位置
beforeDel: {
page: 1, // 当前列表加载的页数
index: 0 // 删除笔记的位置
}
}
},
methods: {
// 获取笔记列表
getList () {
return api.getlist(this.condition).then(res => {
if (res.error_code === 0) {
res.data.forEach(item => {
this.list.push(item)
})
// 默认选中第一个笔记,展示详情
if (this.list.length > 0 && this.condition.page === 1 && Number(this.beforeDel.index) === 0){
this.nowInfo = this.list[0]
this.nowIndex = 0
}
}
})
},
// 删除一条笔记
delOne (val) {
api.del({id: val.id}).then(res => {
if (res.error_code === 0) {
// 如果删除的是当前选中的笔记
if (this.nowInfo.id === val.id) {
this.beforeDel.index = this.nowIndex
} else {
let delIndex = 0
for (const i in this.list) {
if (this.list[i].id === val.id) {
delIndex = i
break
}
}
if (delIndex > this.nowIndex) { // 删除的笔记在当前选中之后
this.beforeDel.index = this.nowIndex + 1
} else { // 删除的笔记在当前笔记之前
this.beforeDel.index = this.nowIndex
}
}
this.beforDel.page = this.condition.page
this.condition.page = 1
this.refreshList()
}
})
},
// 刷新笔记列表
refreshList () {
this.getList().then(() => {
if (this.condition.page < this.beforeDel.page) { // 如果页面小于删除前的页面,将继续调接口获取数据
this.condition.page += 1
this.refreshList()
} else {
// 如果不是第一个,选中上一个笔记(或不改变原选中笔记)
if (Number(this.beforeDel.index) !== 0 && this.list.length > 0) {
this.nowInfo = this.list[this.beforeDel.index - 1]
this.nowIndex = this.beforeDel.index - 1
}
this.beforeDel = {
page: 1,
index: 0
}
}
})
}
}
思路:保存删除前已加载的页数(page)和选中笔记的位置(index),删除成功后,从第一页重新加载数据,直至到删除前列表页数;根据index,设置选中项。