在vuex里 我想統一管理異步的操作,受到redux-thunk的啟發,可以讓vuex派發action,在action執行異步請求axios,在把異步獲取的數據到mutation,但感覺這么做會把接口數據跟state綁定,感覺還是按照具體環境靈活應用較好。
假如我組件的mounted 有這么個獲取接口數據的方法 getGene
getGene(){ this.$store.dispatch('getGeneAction'); //getDatamingData().then(this.getGeneSucc); /* axios.get(urlApi.datamining) .then(this.getGeneSucc); */ },
*注釋掉的是以前直接在方法中獲取接口數據
在我的store里actions.js
getGeneAction(ctx,item){ console.log('getGeneAction'); //調用axios getDatamingData().then((res) => { ctx.commit('GETGENEMUTATION',res); }); }
派發一個GETGENEMUTATION mutation
GETGENEMUTATION(state,item){ //console.log(item.data.obj); state.geneObj = item.data.obj; }
這樣就有了一個vuex
我之前的做法是在父組件獲取異步數據 然后把數據再派發給子組件 子組件在對數據進行vuex操作 。
具體如何管理數據還是看具體的環境。