programing

Vuex: 작업이 완료될 때까지 기다리는 방법

prostudy 2022. 8. 7. 16:08
반응형

Vuex: 작업이 완료될 때까지 기다리는 방법

로그인 방법을 구현하고 싶습니다.내 코드는 다음과 같습니다.

login() {
  let user = {
    email: this.email,
    password: this.password
  };

  this.$store.dispatch('auth/login', user)
  console.log(this.$store.getters['auth/getAuthError'])
},

스토어에 접속하여 로그인 액션을 디스패치합니다.

스토어의 액션은 다음과 같습니다.

login(vuexContext, user) {
        return axios.post('http://localhost:8000/api/user/login', user)
        .then(res => {
            vuexContext.commit('setToken', res.data.token)
            vuexContext.commit('setUser', res.data, {root: true})
            localStorage.setItem('token', res.data.token)
            Cookie.set('token', res.data.token )
            this.$router.push('/')
        }).catch(err => {
            vuexContext.commit('setAuthError', err.response.data)
        })
    },

catch block에서 오류가 발생하면 상태를 업데이트하여 설정합니다.authError에러에 대한 속성입니다.

문제는 로그인 방법에서console.log스테이트먼트는 액션이 실제로 종료되기 전에 실행되므로,authErrorproperty는 상태가 아직 설정되지 않은 것입니다.이 문제를 해결하는 방법

당신의.action를 반환하고 있습니다.promise그 때문에, 그 약속이 해결된 후, 위안을 삼을 수 있습니다.then()차단합니다.

login() {
  let user = {
    email: this.email,
    password: this.password
  };

  this.$store.dispatch('auth/login', user).then(() => {
   console.log(this.$store.getters['auth/getAuthError'])
   // this.$router.push('/') // Also, its better to invoke router's method from a component than in a store file, anyway reference of a component may not be defined in the store file till you explicity pass it
  })
},

또는 로그인을async기능 및wait를 위해action행동으로 돌아온 약속이 해결까지.

async login() {
  let user = {
    email: this.email,
    password: this.password
  };

  await this.$store.dispatch('auth/login', user)
  console.log(this.$store.getters['auth/getAuthError'])
},

Promise. 대신 비동기-ait를 사용할 수 있습니다.하지만 매장 내에서는 Axios를 사용하지 않는 것이 좋습니다.로그인 메서드 내의 Axios를 호출하여 스토어에 문의합니다.다음과 같은 경우:

methods: {
    async login() {
        try {
            const result = await axios.post('http://localhost:8000/api/user/login', this.user);
            this.$store.dispatch('auth/login', result);
        } catch (err) {
            console.log(err);
        }
    }
}

그런 다음 스토어에서 오브젝트를 설정하기만 하면 됩니다.

언급URL : https://stackoverflow.com/questions/60864779/vuex-how-to-wait-for-action-to-finish

반응형