반응형
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
반응형
'programing' 카테고리의 다른 글
| VueJS 싱글 파일 컴포넌트(타이프 스크립트 포함):모듈 정보를 찾을 수 없습니다.표시하다 (0) | 2022.08.07 |
|---|---|
| VueJ가 계산한 속성이 HTML 코드를 반환하는 경우 어떻게 처리합니까? (0) | 2022.08.07 |
| Vue-cli를 사용하여 CSS를 "dist/vue-COMPONT_NAME.js" 파일에 빌드할 수 있습니까? (0) | 2022.08.07 |
| priority 사용방법큐? (0) | 2022.08.07 |
| Clang이 초과 부동소수점 정밀도에 어떻게 대처하는지 설명하는 문서가 있습니까? (0) | 2022.08.07 |