반응형
vue 구성 요소의 vuex 저장소에서 응답 에이잭스를 가져오려면 어떻게 해야 합니까?
내 컴포넌트는 다음과 같습니다.
<template>
...
</template>
<script>
import {mapActions, mapGetters} from 'vuex'
export default {
...
methods: {
add(event) {
this.addProduct(this.filters)
console.log(this.getStatusAddProduct)
if(this.getStatusAddProduct) {
...
}
},
...mapActions(['addProduct'])
},
computed: {
...mapGetters(['getStatusAddProduct'])
}
}
</script>
다음 코드:this.addProduct(this.filters)
addProduct 메서드 및 모듈 vuex를 호출합니다.
모듈 vuex는 다음과 같습니다.
import { set } from 'vue'
import product from '../../api/product'
import * as types from '../mutation-types'
// initial state
const state = {
statusAddProduct: null
}
// getters
const getters = {
getStatusAddProduct: state => state.statusAddProduct
}
// actions
const actions = {
addProduct ({ dispatch, commit, state }, payload)
{
product.add(payload,
data => {
commit(types.ADD_PRODUCT_SUCCESS)
},
errors => {
commit(types.ADD_PRODUCT_FAILURE)
}
}
}
}
// mutations
const mutations = {
[types.ADD_PRODUCT_SUCCESS] (state){
state.statusAddProduct = true
},
[types.ADD_PRODUCT_FAILURE] (state){
state.statusAddProduct = false
}
}
export default {
state,
getters,
actions,
mutations
}
다음 코드:product.add(payload,
vuex 모듈에서는 api를 호출합니다.
api는 다음과 같습니다.
import Vue from 'vue'
export default {
add (filter, cb, ecb = null ) {
axios.post('/member/product/store', filter)
.then(response => cb(response))
.catch(error => ecb(error))
}
}
여기서의 문제는 vue 컴포넌트에서 메서드를 추가하면 다음과 같은 결과가 발생한다는 것입니다.console.log(this.getStatusAddProduct)
null 입니다.제품의 성공이 더해진다면, 그 결과는console.log(this.getStatusAddProduct)
맞다
이런 일이 일어나는 건 도망갈 때console.log(this.getStatusAddProduct)
vuex 모듈의 제품 추가 프로세스가 아직 완료되지 않았습니다.결과는 무효입니다.
어떻게 하면console.log(this.getStatusAddProduct)
vuex 모듈의 프로세스가 완료되면 실행하시겠습니까?
당신은 그 부동산을 계속 넘겨야 합니다..add()
방법.
중간 방법으로 반환하고 마지막으로 다음을 사용하여 반환해야 합니다..then()
.
API:
add (filter, cb, ecb = null ) {
return axios.post('/member/product/store', filter) // added return
.then(response => cb(response))
.catch(error => ecb(error))
}
그리고...action
:
addProduct ({ dispatch, commit, state }, payload) // added return
{
return product.add(payload,
data => {
commit(types.ADD_PRODUCT_SUCCESS)
},
errors => {
commit(types.ADD_PRODUCT_FAILURE)
}
}
}
마지막으로:
methods: {
add(event) {
this.addProduct(this.filters).then(() => { // added then
console.log(this.getStatusAddProduct) // moved inside then
if(this.getStatusAddProduct) {
...
}
})
},
언급URL : https://stackoverflow.com/questions/49503251/how-can-i-get-response-ajax-by-vuex-store-in-the-vue-component
반응형
'programing' 카테고리의 다른 글
구성 요소 라이브러리의 Vuex 저장소 (0) | 2022.08.07 |
---|---|
if(1 | | !Foo()를 사용하는 이유가 있습니까? (0) | 2022.08.07 |
Vue 표 2 - 커스텀필터 (0) | 2022.08.07 |
node_modules에서 동적 Vue 이미지 src 바인딩 (0) | 2022.08.07 |
String.valueOf()와오브젝트.toString() (0) | 2022.08.07 |