Search code examples
javascriptvue.jsvuejs2vuexvuex-modules

How to pass data from vuex store through module to vue component?


I'm able to console data, as well as able to see data in vuex dev tool but not able to display them in table. Please if someone could check my code and tell me what is wrong with it. Thanks folks. I tried differents methods like async/await, promise, getters... but I was not able to to get the data, probably I was not calling it properly.

ROLE.VUE

<emplate>
  <di>
    <p v-for="(role, index) in roles :key="index">
  </div>
</template>

<script>

import { mapState } from 'vuex'

export default ({
  name: 'Role',
  metaInfo: {
    title: 'Role'
  },

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

  computed: {
    ...mapState([
      'roles'
    ])
  }
})

</script>

role.js

import Axios from 'axios'

export default {
//   namespaced: true,

  state: {
    roles: [],
  },

  getters: {
    roles (state) {
      return state.roles
    }
  },

  mutations: {
    SET_ROLES (state, roles) {
      state.roles = roles
    }
  },

  actions: {

loadRoles ({ commit }) {
  Axios.get('/settings/roles')
    .then((response) => {
      console.log(response.data)
      //   let roles = response.data
      commit('SET_ROLES', response.data.roles)
    })
}

} }

index.js

import role from './role'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {

  },

  mutations: {
    //
  },

  modules: {
    role
  },

  actions: {
    //
  }
})

Main.js

import { store } from './store/store'
new Vue({
router,
store,
ValidationProvider,
render: h => h(App)
})

Solution

  • When loading from a module with mapState, you need to specify the name of the module you are loading from. Here is the proper syntax for your case:

    ...mapState('role', ['roles'])
    

    The first argument is the module name, and the second is an array of state properties from that module.