【问题标题】:Nuxt vuex state menuList:undefined in componentNuxt vuex状态菜单列表:组件中未定义
【发布时间】:2021-05-27 12:23:06
【问题描述】:

伙计。我是新手程序员。

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

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

如何在 nuxt 中使用 getter。

此图像来自开发工具。

在 getter 和状态变化中:menuList 有数组数据,但在组件中没有数据。

此图片来自组件

组件 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
  }
}

Chachang/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
}

【问题讨论】:

    标签: javascript vue.js nuxt.js vuex


    【解决方案1】:

    试试这个。

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

    【讨论】:

      【解决方案2】:

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

      从 'vuex' 导入 { mapGetters, mapActions }

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

      【讨论】:

      • 嗨,Levy_from_Odessa 它可以工作,但我认为这不适合我解决问题。
      猜你喜欢
      • 2019-08-17
      • 2018-08-09
      • 2020-05-28
      • 2018-10-11
      • 2020-09-10
      • 2018-09-22
      • 2020-08-11
      • 2020-11-18
      • 1970-01-01
      相关资源
      最近更新 更多