1. axios 正常用法:
export default {
name: 'Historys',
data() {
return {
totalData: 0,
tableData: []
}
},
created () {
this.getHistoryData()
},
methods: {
handleClick (tab) {
let data = {
status: tab.name,
name: this.formInline.user,
cid: this.formInline.identity,
start_time: this.formInline.dateTime ? this.formInline.dateTime[0] : '',
end_time: this.formInline.dateTime ? this.formInline.dateTime[1] : ''
}
this.getHistoryData()
},
// 統一處理axios請求
getHistoryData (data) {
axios.get('/api/survey/list/', {
params: data
}).then((res) => {
console.log(res)
this.tableData = res.data.result
this.totalData = res.data.count
}).catch((err) => {
console.log(err)
alert('請求出錯!')
})
}
}
}
2. 使用 asyns/await 将 axios 異步請求同步化:
2.1 當 axios 請求拿到的資料在不同場景下做相同的處理時:
export default {
name: 'Historys',
data() {
return {
totalData: 0,
tableData: []
}
},
created () {
this.getHistoryData()
},
methods: {
handleClick (tab) {
let data = {
status: tab.name,
name: this.formInline.user,
cid: this.formInline.identity,
start_time: this.formInline.dateTime ? this.formInline.dateTime[0] : '',
end_time: this.formInline.dateTime ? this.formInline.dateTime[1] : ''
}
this.getHistoryData()
},
// 統一處理axios請求
async getHistoryData (data) {
try {
let res = await axios.get('/api/survey/list/', {
params: data
})
this.tableData = res.data.result
this.totalData = res.data.count
} catch (err) {
console.log(err)
alert('請求出錯!')
}
}
}
}
2.2 當 axios 請求拿到的資料在不同場景下做不同的處理時:
export default {
name: 'Historys',
data() {
return {
totalData: 0,
tableData: []
}
},
async created () {
try {
let res = await this.getHistoryData()
console.log(res)
// 等拿到傳回資料res後再進行處理
this.tableData = res.data.result
this.totalData = res.data.count
} catch (err) {
console.log(err)
alert('請求出錯')
}
},
methods: {
async handleClick (tab) {
let data = {
status: tab.name,
name: this.formInline.user,
cid: this.formInline.identity,
start_time: this.formInline.dateTime ? this.formInline.dateTime[0] : '',
end_time: this.formInline.dateTime ? this.formInline.dateTime[1] : ''
}
try {
let res = await this.getHistoryData()
console.log(res)
// 等拿到傳回資料res後再進行處理
this.tableData = res.data.result
this.totalData = res.data.count
} catch (err) {
console.log(err)
alert('請求出錯')
}
},
// 封裝axios請求,傳回promise, 用于調用getHistoryData函數後作不同處理
getHistoryData (data) {
return new Promise((resolve, reject) => {
axios.get('/api/survey/list/', {
params: data
}).then((res) => {
resolve(res)
}).catch((err) => {
reject(err)
})
})
}
}
}