Nuxt vuex 状态菜单列表:组件中未定义

发布时间:2021-02-25 06:33

伙计。我是新手程序员。

我对 nuxt 使用 vuex 获取 api 数据有疑问。

所以 vue 中的数据调用值为 null 但在开发工具中 vue 有数据。

如何在 nuxt 中使用 getter。

这张来自开发工具的图片。 enter image description here

在 getter 和 state chachange 中:menuList 有数组数据,但在组件中没有数据。

这张图片来自组件 enter image description here

Component MenuList> 计算的> menuList:未定义。

这是我的 menu_list.vue 代码。

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')
  }

这个 vuex 代码。 茶场/state.js

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

茶场/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
  }
}

茶仓/getters.js

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

这家商店/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
}
回答1

我建议你使用从 vuex 导入的 mapActions 和 mapGetters。

从'vuex'导入{ mapGetters, mapActions }

export default{
...
   methods:{
      ...mapActions('chachang',[ 'fetchMenu' ])
   },
   mounted(){
      this.fetchMenu() // better to use fetchData instead 
   }
   computed:{
      ...mapGetters('chachang', [ 'menuList' ])
   }

..
}
回答2

试试这个。

  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']
        }
      },