如何在Vuex中执行下一个动作之前等待状态更改

问题描述 投票:1回答:1

我正在尝试同时登录并获取用户名。它是这样工作的:

  1. 第一个动作login获取访问令牌并更新state.accessToken
  2. 使用state.accessToken我需要在按下登录键的同时获取用户数据(fetchUser),但是当执行fetchUserstate.accessToken仍为null,因为操作是异步的。在执行下一个动作之前等待状态改变的最佳实践是什么?我试图查找示例,但是找到的解决方案不适用于我的情况。

store.js

const store = new Vuex.Store({

state: {
  accessToken: null,
  user: null
},

mutations: {
  authUser (state, userData) {
    state.accessToken = userData.accessToken
  },
  storeUser (state, user) {
    state.user = user
  }
}

actions: {
  login({commit}, authData) {
    axios.post("http://example.com/token/create/", {
        email: authData.email,
        password: authData.password
      })
      .then(res => {
        commit('authUser', {
          accessToken: res.data.access
        })
      })
  },
  fetchUser({commit, state}) {
    axios.get("http://example.com/api/auth/v1/me/", {
      headers: {Authorization: "Bearer "  + state.accessToken}
    })
    .then(res => {
      commit('storeUser', res.data.user)
    })
  }
}

getters: {
  user (state) {
    return state.user
  },
  isAuthenticated(state) {
    return state.accessToken !== null
  }  
}
})

login.vue

<template>
  <form @submit.prevent="submitForm">
    <div v-if="!auth" class="row">
      <input class="col" placeholder="Email" v-model="formInfo.email" type="text"></input>
      <input class="col" placeholder="Password" v-model="formInfo.password" type="password"></input>
      <button class="col" type="submit"  label="Log In"></button>
    </div>
    <div v-else class="row">
      Hello {{ firstname }}
    </div>
  </form>
</template>

<script>
  export default {
    data() {
      return {
        formInfo: {
          email: '',
          password: ''
        }
      };
    },
    methods: {
      submitForm() {
        this.$store.dispatch('login', {email: this.formInfo.email, password: this.formInfo.password})
        this.$store.dispatch('fetchUser')
      }
    },
    computed: {
      auth() {
        return this.$store.getters.isAuthenticated
      },
      firstname() {
        return this.$store.getters.user.firstname
      }    
    }
  }
  };
</script>
vue.js vuejs2 axios vuex
1个回答
0
投票
async submitForm() { await this.$store.dispatch('login', {email: this.formInfo.email, password: this.formInfo.password}); await this.$store.dispatch('fetchUser'); }

它将在获取用户之前等待登录完成

也可以在您的操作方法中添加异步:

async login({commit}, authData) {...} async fetchUser({commit, state}) {...}

© www.soinside.com 2019 - 2024. All rights reserved.