實現同步重點在於添加async、await,且後臺請求方法與調用者都需要添加,也就是添加兩組,經測試單獨添加任何一組都無效
axios封裝的請求, user.js
import axios from '@/libs/api.request'
export const getAllUser = (data) => {
return axios.request({
url: 'user/mgt/getAllUser',
method: 'post',
data: data
})
}
方法調用與同步請求
import { getAllUser } from '@/api/user'
// 方法調用
async getList(){
let _this = this
await getAllUser({
queryParams: JSON.stringify(this.search),
type: 1
}).then(res => {
debugger
let { data, total } = res.data.data
this.list = {
data: data,
total: total,
loading: false
}
}).catch(err => {
console.log(err)
})
},
// 調用getList方法
async showModal (name, userIds, userNames) {
this.modal.visible = true
this.selectData.ids = userIds
this.selectData.alias = userNames
await this.getList(userIds)
debugger
let users = []
if (userIds && this.list.data) {
users = userIds.split(",")
users.forEach((item, index, users) => {
for (let i=0;i<this.list.data.length;i++) {
debugger
if (this.list.data[i].id === item) {
this.$refs.table.$refs.tbody.objData[i]._isChecked = true;
}
}
})
}
},
說明:因爲需要getList()方法執行完成之後才允許執行let users = []之後的代碼,所以getList()必須要加同步,代碼中debugger調試後會發現先執行完axios請求並且從服務器返回數據之後才執行下面的代碼