반응형
Vuex 디스패치에 의한 비동기/대기
앱에 있는 몇 가지 컴포넌트의 로더를 만들고 있습니다.
내 컴포넌트는 다음과 같습니다.
mounted() {
this.loading = true;
this.getProduct();
},
methods: {
async getProduct() {
await this.$store.dispatch('product/getProducts', 'bestseller');
console.log(123);
this.loading = false;
}
},
Vuex 액션:
getProducts({commit}, type) {
axios.get(`/api/products/${type}`)
.then(res => {
let products = res.data;
commit('SET_PRODUCTS', {products, type})
}).catch(err => {
console.log(err);
})
},
문제는 다음 행에 있습니다.await this.$store.dispatch('product/getProducts', 'bestseller');
코드가 그 라인에서 정지하고 AJAX 콜에서 데이터가 로드되기를 기다렸다가 로딩이 다음과 같이 설정될 것으로 예상합니다.false
;
하지만 그렇지는 않다.로딩이 아직 설정되었습니다.false
및 그console.log
데이터가 준비되기 전에 실행할 수 있습니다.
이미 비동기/대기 상태를 Vuex 작업으로 이동하려고 시도했지만 정상적으로 작동했습니다.하지만 나는 그들 사이의 차이를 이해하지 못했다.
아래 코드는 나에게 유효합니다.
컴포넌트:
mounted() {
this.loading = true;
this.$store.dispatch('product/getProducts', 'bestseller').then((res) => {
this.loading = false;
});
},
Vuex 액션:
async getProducts({commit}, type) {
let res = await axios.get(`/api/products/${type}`);
commit('SET_PRODUCTS', {products: res.data, type});
}
변경:
getProducts({commit}, type) {
axios.get(`/api/products/${type}`)
.then(res => {
let products = res.data;
commit('SET_PRODUCTS', {products, type})
}).catch(err => {
console.log(err);
})
},
이를 위해:
getProducts({commit}, type) {
return axios.get(`/api/products/${type}`)
.then(res => {
let products = res.data;
commit('SET_PRODUCTS', {products, type})
}).catch(err => {
console.log(err);
})
},
될 거야.
axios.get
약속을 반환합니다.그 약속을 돌려주셔야 합니다await
기다려봐.그렇지 않으면 암묵적으로 반환됩니다.undefined
그리고.await undefined
즉시 해결됩니다.
약속 없이 행사를 기다릴 수는 없다.
await this.$store.dispatch('product/getProducts', 'bestseller');
이 함수는 데이터를 반환하거나 새 작업을 호출합니다.
getProducts({commit}, type) {
axios.get(`/api/products/${type}`)
.then(res => {
let products = res.data;
commit('SET_PRODUCTS', {products, type})
}).catch(err => {
console.log(err);
})
},
그리고 이 함수는 비동기 함수로 인해 약속을 반환합니다.
async function return promise
async getProducts({commit}, type) {
let res = await axios.get(`/api/products/${type}`);
commit('SET_PRODUCTS', {products: res.data, type});
}
이제 위의 기능을 사용하여
await this.$store.dispatch('product/getProducts', 'bestseller');
wait 키워드와 함께 또는 공리도 약속을 반환하기 때문에 공리도 반환할 수 있습니다.
언급URL : https://stackoverflow.com/questions/55700815/async-await-with-vuex-dispatch
반응형
'programing' 카테고리의 다른 글
C 코드의 스위치 케이스에 있는 "..."는 무엇입니까? (0) | 2022.07.21 |
---|---|
영구 스토리지에서 저장소 수분을 보충한 후 Vuex getter가 업데이트되지 않음 (0) | 2022.07.21 |
VueJ 2.0에서 vee-validate를 사용하는 두 필드 중 하나 이상 필요 (0) | 2022.07.21 |
Ubuntu 시스템에 Python이 있는데 gcc가 Python.h를 찾을 수 없습니다. (0) | 2022.07.21 |
VueJs 2를 사용한 글로벌 데이터 (0) | 2022.07.21 |