Search code examples
vue.jsvuejs2vuex

How to use shorter path to get vuex contents?


In my vuex /store/state.js I have an export default that looks like this:

export default {
  foo: {
    bar:{
      tar: {
        info: 42
      }
    } 
  }
} 

So, whenever I want to access info, I usually do in my methods like this;

methods: {
  getInfo () {
   return this.$store.state.foo.bar.tar.info
  }
}

This is just for a demo purpose, and mine is actually a bit worse, but I ended up doing the same so, I tried minimize the code using a computed prop:

computed: {
  info () {
    return this.$store.state.foo.bar.tar.info
  }
}

Now, I just call info but still, not sure if there is a better way to get values, because sometimes I just need to call info only one in a page, so I have to use the full path or create a computed property for it.

Is there any other way to do this


Solution

  • I always separate vuex into separated modules. For instance if you have store for foo module. I will create file named foo.js which contains

    const fooModule = {
      state: {
        foo: {
          bar: {
            tar: {
              info: 42
            }
          }
        }
      },
      getters: {
        info (state) {
          return state.foo.bar.tar.info
        }
      },
      mutations: {
        setInfo (state, payload) {
          state.foo.bar.tar.info = payload
        }
      },
      actions: {
        getInfo ({commit}, payload) {
          commit('setInfo', payload)
        }
      }
    }
    
    export default fooModule
    

    Then in your main index vuex, import the module like this way

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    import fooModule from './foo.js'
    
    Vue.use(Vuex)
    
    const store = new Vuex.Store({
      modules: {
        fooModule
      }
    })
    
    export default store
    

    Then if you wanna get info, you just write your code like this

    import { mapGetters } from 'vuex';
    
    export default {
      computed: {
        ...mapGetters([
          'getInfo'
        ])
      }
    }