【问题标题】:How to dispatch store action within fetch function in nuxt?如何在 nuxt 的 fetch 函数中调度存储操作?
【发布时间】:2020-11-11 01:02:19
【问题描述】:

我有一个使用 nuxt Universe SSR 的项目。我使用 fetch 方法获取布局数据,触发存储操作调度。但它根本不起作用......

这是代码。这是默认布局文件:

import Navbar from '~/components/Navbar'

export default {
  components: {
    Navbar
  },
  async fetch ({ store }) {
    await store.dispatch('fetchItems')
  }
}

这里是 vuex 商店:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = () => new Vuex.Store({

  state: {
    allItems: [],
    currentCategories: []
  },
  mutations: {
    setItems (state, allItems) {
      state.allItems = allItems
    },
    setCurrentCategories (state, currentCategories) {
      state.currentCategories = currentCategories
    }
  },
  actions: {
    async fetchItems ({ commit, dispatch }) {
      try {
        const { data: { items } } = await this.$axios.get('/api/catalog/categories?limit=0')
        commit('setItems', items)
        dispatch('getCurrentCategories')
      } catch (e) {
        console.error(e)
      }
    },
    getCurrentCategories ({ commit }, payload) {
      const newCategories = []
      if (!payload) {
        this.state.allItems.forEach((item) => {
          if (!item.parent_id) {
            newCategories.push(item)
          }
        })
      } else {
        this.state.allItems.forEach((item) => {
          if (item.parent_id === payload) {
            newCategories.push(item)
          }
        })
      }
      commit('setCurrentCategories', newCategories)
    }
  },
  getters: {
    allItems: s => s.allItems,
    currentCategories: s => s.currentCategories
  }
})

export default store

似乎 fetch 方法根本没有触发。我试图在 fetch 方法中的 console.log 中放置一些东西,但我在控制台中看不到任何输出......我是 nuxt 的新手,我以前使用过 vue。任何建议都非常感谢。

【问题讨论】:

  • 没人帮忙吗?你找到解决方案了吗?谢谢
  • 您找到解决方案了吗?

标签: fetch vuex nuxt.js server-side-rendering


【解决方案1】:

改为这样做:

async fetch () {
  await this.$store.dispatch('fetchItems')
}

【讨论】:

    【解决方案2】:

    如果函数没有被触发,可能是它的路径不正确。 Nuxt 建议将 Vuex 与模块一起使用:https://nuxtjs.org/docs/2.x/directory-structure/store

    每个模块都是namespaced

    因此,在您的情况下,我将在 store 目录中创建一个 items.js 文件。 而且,在布局文件中,我会触发这样的功能:

    store.dispatch('items/fetchItems');
    

    【讨论】:

      猜你喜欢
      • 2020-02-23
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      • 2021-06-13
      • 2019-05-01
      • 2020-10-24
      相关资源
      最近更新 更多