如何在vue组件中通过vuex store获取响应ajax?

时间:2018-03-27 01:57:22

标签: vue.js vuejs2 vue-component vuex vuex-modules

我的组件如下:

<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),它将在模块vuex中调用addProduct方法

我的模块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组件中的add方法,console.log(this.getStatusAddProduct)的结果为null。如果添加了产品成功,则console.log(this.getStatusAddProduct)的结果为真

我认为这是因为在运行console.log(this.getStatusAddProduct)时,在vuex模块中添加产品的过程尚未完成。所以结果是null

如何在vuex模块中的进程完成后运行console.log(this.getStatusAddProduct)

1 个答案:

答案 0 :(得分:1)

您必须从.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) {
                ...
            }
        })
    },