首页 > 解决方案 > nativescript 等待请求,直到 vuex 完成请求

问题描述

我有页面 Login.vue,如果用户已经登录,我正在使用一种策略,然后转到主页组件,否则保持不变

我的代码

mounted() {
  this.checkAlreadyLoggedIn();
},
methods: { 
 async checkAlreadyLoggedIn() {
   this.busy = true;
   await this.$store.dispatch("attempt");
   this.busy = false;
   if (this.$store.getters.loggedIn) {
     this.$navigateTo(Home, {
      clearHistory: true
     });
   }
 },
}

尝试对服务器的操作请求并获取用户详细信息,但它似乎很this.$store.getters.loggedIn早就触发了

谢谢

标签: vue.jsvuejs2nativescriptvuexnativescript-vue

解决方案


In order to wait properly before checking the getter, and trigger the busy state, return the promise from the attempt action:

attempt({ state, commit }) {
  return axios.post(...)  // <-- Returning the promise manually
  .then(response => {
    // Commit change
  })
},

Or with async / await:

async attempt({ state, commit }) { // <-- async keyword returns promise automatically
  const response = await axios.post(...);
  // Commit change
}

Here is a demo


推荐阅读