programing

nuxt의 가져오기 함수 내에서 스토어 액션을 디스패치하려면 어떻게 해야 합니다.

prostudy 2022. 7. 25. 22:18
반응형

nuxt의 가져오기 함수 내에서 스토어 액션을 디스패치하려면 어떻게 해야 합니다.

nuxt universe SSR를 이용한 프로젝트가 있습니다.fetch method를 사용하여 레이아웃 데이터를 가져오고 스토어 액션 디스패치를 트리거합니다.근데 전혀 안 먹히는데...

여기 암호가 있습니다.기본 레이아웃 파일입니다.

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 메서드는 전혀 트리거되지 않는 것 같습니다.가져오기 메서드에서 console.log에 뭔가를 넣으려고 했지만 콘솔에 출력이 표시되지 않습니다...저는 nuxt는 처음이라서 vue를 써봤어요.어떤 제안이라도 대단히 감사합니다.

대신 다음을 수행합니다.

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

함수가 트리거되지 않으면 해당 경로가 잘못되었을 수 있습니다.Nuxt는 Vuex를 모듈과 함께 사용할 것을 권장합니다.https://nuxtjs.org/docs/2.x/directory-structure/store

각 모듈은namespaced.

그래서, 당신의 경우엔, 제가 만든게items.js파일을 저장합니다.그리고 레이아웃 파일에서는 다음과 같은 함수를 트리거합니다.

store.dispatch('items/fetchItems');

언급URL : https://stackoverflow.com/questions/63018065/how-to-dispatch-store-action-within-fetch-function-in-nuxt

반응형