在Vuex存储中捕获Axios异常并将其抛出到Vue.js方法

时间:2018-02-28 17:16:54

标签: vue.js axios vuex

如何在 vuex 商店中捕获 axios 例外并将其投放到 vue.js 方法?我的目标是让此异常能够使用input重置绑定到this.$forceUpdate()的计算值。

在我的方法中,我有这个:

methods: {
    mymet: _.debounce(
        function(table, id, key, event) {
            const value = event.target.value;
            this.$store.dispatch('UPDATE_TRANSACTIONS_ITEM', { table, id, key, value }).then(response => {
                event.target.classList.remove("is-invalid")
                event.target.classList.add("is-valid")
            }, error => {
                console.error("Got nothing from server. Prompt user to check internet connection and try again")
                this.$forceUpdate();
            })
        }, 500
    )
}

在我的vuex商店,我有这个:

const actions = {
    UPDATE_TRANSACTIONS_ITEM ({ commit }, data) {
        let company = {
            [data.key]: data.value
        }
        axios.put(`/api/companies/${data.id}`, { company }).then( function ( response ) {
            commit('SET_TRANSACTIONS_ITEM_UPDATE', { profile: data })
        }).catch(function (error) {
            throw error
        })
    }
}

const mutations = {
    SET_TRANSACTIONS_ITEM_UPDATE (state, { profile }) {
        state.company_data[profile.key] = profile.value
    },
}

1 个答案:

答案 0 :(得分:1)

您需要使实际的动作函数异步。

如果你有能力使用async functions,你可以等待MinT = {month_num + 1: [] for month_num in range(12)} 调用,让错误冒出来(不需要在动作中抛出任何东西):

axios

否则,您需要返回Promise并捕获错误并将其传递给const actions = { async UPDATE_TRANSACTIONS_ITEM ({ commit }, data) { let company = {[data.key]: data.value}; await axios.put(`/api/companies/${data.id}`, { company }).then(() => { commit('SET_TRANSACTIONS_ITEM_UPDATE', { profile: data }) }); } } 处理程序:

reject
相关问题