Hindsight 20:20编辑-此question解决了真正的潜在问题,在遇到以下问题时并不明显。将此问题/答案留作后代。
我有一个VueJS前端,其Django REST API后端带有多个端点。
我无法上班的用户流程:
如何基于此Vuex Store变量有条件地重定向到“通过”页面(有进一步的操作)或“失败”页面?
BasePage.vue
<script>
import { mapState, mapActions } from "vuex";
export default {
name: "basepage",
components: {
...stuff...
},
data() {
return {
data: [],
};
},
methods: {
...mapActions("results", ["addNormalResults", "addVPCResults"]),
getStats() {
const payload = this.buildDataPayload;
//this calls the store page to update the store with response data
this.addNormalResults(payload).then(() => {
// eslint-disable-next-line
console.log('normal finished');
const result = this.normalResults;
console.log(result); //always is empty
});
},
clearData() {
this.data = [];
}
},
computed: {
...mapState("results", ["normalResults"]),
}
results.js store page
import statsEndpoints from '../../services/statsEndpoints'
const state = {
'normalResults': 'empty',
'vpcResults': 'empty',
}
const getters = {
normalResults: state => {
return state.normalResults
},
vpcResults: state => {
return state.vpcResults
}
}
const actions = {
addNormalResults({commit}, payload) {
statsEndpoints.postNormality(payload)
.then(response => {
commit('addNormal', response)
})
},
addVPCResults({
commit
}, payload) {
statsEndpoints.postVPC(payload)
.then(response => {
commit('addVPC', response)
})
}
}
const mutations = {
addNormal(state, response) {
state.normalResults = response
},
addVPC(state, response){
state.vpcResults = response
}
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
答案 0 :(得分:0)
找出答案并回答我的后代问题:
真正的问题是vuex的异步操作。提交时它会异步完成“ addNormalResults”操作,因为statsEndpoints.postNormality 的承诺没有返回到我的Vue组件中的函数。
如果在操作中返回了Promise,则可以使用.then( ()=> {do stuff}
来解决Promise,然后执行do stuff
。
更改为results.js store page
:
const actions = {
addNormalResults({commit}, payload) {
return statsEndpoints.postNormality(payload) //notice the return
.then(response => {
commit('addNormal', response)
})
}
}
答案 1 :(得分:-1)
成功时,您可以在商店中调用一个操作,将其值设置为true,当发生错误时,将其值设置为false,然后在组件内部调用一个getter,在其中调用函数并使用该getter进行操作。像这样重定向用户
if(sucess){
this.$router.replace({
path:'to success path',query:{
id:your query 'optional'
}
})
}else{
this.$router.replace({
path:'to error path',query:{
id:your query 'optional'
}
})
}