Search code examples
javascriptvue.jsnuxt.jsvuex

Nuxt vuex state menuList:undefined in component


guy. I'm novice programmer.

I have question for nuxt use vuex get data for api.

so data call in vue value null but in dev tool vue has data.

How to use getters in nuxt.

This image from dev tool. enter image description here

In getters and state chachange: menuList has array data but in component not data.

This image from component enter image description here

Component MenuList> computed> menuList: undefined.

This my menu_list.vue code.

computed: {
    menuList () {
      // eslint-disable-next-line no-console
      return this.$store.getters.getMenuList
    }
  },
  beforeCreated () {
    // eslint-disable-next-line no-console
    console.log(this.$store.state)
    this.$store.dispatch('chachang/fetchMenu')
  },
  created () {
    // eslint-disable-next-line no-console
    console.log(this.$store.state)
    this.$store.dispatch('chachang/fetchMenu')
  }

This vuex code. Chachang/state.js

export default () => ({
  menuList: []
})

Chachang/actions.js

export default {
  async fetchMenu ({ commit }) {
    const response = await this.$axios.get('https://hlkittipan.github.io/rock-paper-scissors/menu.json')
    commit('SET_MENU', response.data)
  }
}

Chachang/mutations.js

export default {
  SET_MENU (state, menu) {
    state.menuList = menu
  }
}

Chachang/getters.js

export default {
  getMenuList: (state) => {
    return state.menuList
  }
}

This store/index.js

import chachangActions from './chachang/actions'
import chachangStates from './chachang/state'
import chachangGetters from './chachang/getters'
import chachangMutations from './chachang/mutations'

export const state = () => ({
  ...chachangStates.state,
})

export const mutations = {
  ...chachangMutations.mutations, 
}

export const actions = {
  ...chachangActions.actions
}

export const getters = {
  ...chachangGetters.getters
}

Solution

  • Try this.

      async beforeMount () {
            const data = await this.$store.dispatch('chachang/fetchMenu')
            // eslint-disable-next-line no-console
            console.log(data)
          },computed: {
            menuList () {
              // eslint-disable-next-line no-console
              return this.$store.getters['chachang/getMenuList']
            }
          },