简体   繁体   中英

Vuex modules and returning a promise in an action

I want to split my vuex file into modules, but as soon as I do that the promise I return from my action becomes undefined when I console log it in the actual template.

So in my action I have something like

return axios.get(....)

And in my component I have a method that does the following

this.$store.dispatch('setRules').then(response => {console.log(response)})

As soon as I switch from using store.js to importing a module in my store.js file, the response becomes undefined but the rest of vuex still works correctly. When checking the state I also see that the action actually gets executed and the state gets updated, so it seems as if it is a problem with axios.

The new store.js file looks the following:

import Vue from 'vue'
import Vuex from 'vuex'

import stock from './modules/stock';

Vue.use(Vuex);

export default new Vuex.Store( {
    modules: {
        stock,
    }
});

And in my module stock.js I have something like this.

const getters = {..}
const actions = {..}
const mutations = {..}
const state = {..}

export default {
  namespaced: false,
  state,
  mutations,
  actions,
  getters
}

Does anyone have an idea what I am doing wrong?

The above scenerio is happening because javascript is asyncronous and hence before the response from your api call is returned the console statement is executed and hence you see that as undefined.

You can try using async await on axios call as

async actionName ()
{
  await axios.get(..).then(response => { console.log(response)} )
}

So I found out that the problem was caused by the fact that I tried to acces this.$store.state.x while it should be this.$store.state.stock.x . Is there a way to not need the module name to access the state?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM