Search code examples
javascriptvue.jsvue-resourcevuex

Should I use vue-resource on Vuex actions


I am developing a webapp where it fetches airports from back end. I am also using Vuex to share states and data. My question is should I load the airports in my VueX actions or on my vue instance method then call the action that dispatches only the event

Example

// ajax from vuex actions
export const loadAirports = ({dispatch})=>{
    //load data via vue-resource
    dispatch("SET_AIRPORTS",data);
}

or

//action
export const setAirports(({dispatch},airports) =>{
   dispatch("SET_AIRPORTS",airports);
}

new Vue({
    ready(){
        //load data view-resource

        this.setAirports(data); 
    }
})

Solution

  • Mutations should always be synchronous. But it's fine to do your ajax in actions, in fact that is how it is done in many of the official examples. I would do

    import {loadAirports} from './actions.js'
    
    new Vue({
      vuex:{
        actions: {
          loadAirports
        },
        getters: {
          airports: state => state.airports
        }
      },
      ready(){
        this.loadAirports();
      }
    });