這里都是獲取異步axios的請求結果
一、async/await的方式(獲取一個vuex中的異步請求的結果)
1、在vuex(store中的index.js)中定義異步函數
1> 在mutation里定義同步函數,(用來自異步請求的結果)更新state中的值
mutations: { getDbws (state, dbws) { // 引用state和異步的結果dbws
// 修改state里面的值 => state.xx=''
} } }
2> 在action里定義async異步函數,進行axios請求,在返回結果中commit定義在mutation中的函數
actions: { async getDb (ctx) { await axios.get('url') .then((response) => { ctx.commit('getDbws', response.data.data) }).catch((err) => { alert(err) }) } } // 利用傳入的context(ctx)作為載體傳遞參數,而不是直接傳給state // 在action里調用異步請求,使用commit來獲取mutation里的方法,更新state
2、在組件xx.vue中定義異步函數,用來調用vuex中的異步函數,獲取返回值並更新組件中的值
1> 在methods中定義異步函數
getInit: async function () { // 用dispatc啟動命名在action中的異步函數
// 這個請求之前加 await,這樣之后的句子就運行在上一步獲取結果之后
await this.$store.dispatch('getDb') // 用vuex中的異步結果更新組件中的值
this.wsNames = this.$store.state.wsNames }
2> 在created生命周期函數中運行這個函數
created: function () { this.getInit() }
二、promise.all()的方式(獲取多個異步請求的結果)
const Pm = new Promise((resolve, reject) => { if () {axios.put(wmsurl + this.wsName, wmss).then((resolve('promisem')))}
else { resolve('no promisem') } //滿足條件就在if塊內獲取調用異步請求,並在.then中處理resolve //不滿足條件就直接在else中返回resolve。若不進行任何請求便不返回resolve,那promise.all()便永遠都不能執行
}) const Pf = new Promise((resolve, reject) => { }) Promise.all([Pm, Pf]).then((res) => { // 獲取到兩個resolve結果后,也就是Pm,Pf這兩個異步都執行完后,在promise.all()中進行下一步操作
......})