Nuxt Vuex - 如何将 Vuex 模块分解为单独的文件?

新手上路,请多包涵

In the Nuxt documentation ( here ) it says ‘You can optionally break down a module file into separate files: state.js , actions.js , mutations.js and getters.js

我似乎找不到任何关于如何完成此操作的示例 - 许多将根级别的 Vuex 存储分解为 state.js , actions.js , mutations.jsgetters.js ,并放入单独的模块文件中,但与分解模块本身无关。

所以目前我有:

      ├── assets
     ├── components
     └── store
           ├── moduleOne.js
           ├── moduleTwo.js
           └── etc...

我想要的是:

      ├── assets
     ├── components
     └── store
           └── moduleOne
                 └── state.js
                 └── getters.js
                 └── mutations.js
                 └── actions.js
           └── moduleTwo
                └── etc...

要尝试这个,在 /store/moduleOne/state.js 我有:

 export const state = () => {
    return {
        test: 'test'
    }
};

/store/moduleOne/getters.js 我有:

 export const getters = {
    getTest (state) {
        return state.test;
    }
}

在我的组件中,我正在使用 $store.getters['moduleOne/getters/getTest'] 访问它

但是使用调试器和 Vue devtools,似乎无法在 getters 文件中访问状态 - 它似乎正在本地文件中寻找状态,因此 state.test 未定义。

尝试将 state 从我的 state.js 文件导入到我的 getters.js 文件似乎也不起作用。

有没有人举例说明他们如何在 Nuxt 中像这样分解商店?

原文由 Guy Harper 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 532
2 个回答

我正在使用 nuxt 2.1.0 如果你想要这样的东西:

使用 Nuxt 存储模块 Vuex

在我的 store/index.js

确保你有 namespaced: true

 import Vuex from 'vuex';
import apiModule from './modules/api-logic';
import appModule from './modules/app-logic';

const createStore = () => {
  return new Vuex.Store({
    namespaced: true,
    modules: {
      appLogic: appModule,
      api: apiModule
    }
  });
};

export default createStore

在模块一

在我的 store/api-logic/index.js

 import actions from './actions';
import getters from './getters';
import mutations from './mutations';

const defaultState = {
  hello: 'salut I am module api'
}

const inBrowser = typeof window !== 'undefined';
// if in browser, use pre-fetched state injected by SSR
const state = (inBrowser && window.__INITIAL_STATE__) ? window.__INITIAL_STATE__.page : defaultState;

export default {
  state,
  actions,
  mutations,
  getters
}

在我的 store/api-logic/getters.js

 export default {
  getHelloThere: state => state.hello
}

在模块二

在我的 store/app-logic/index.js

 import actions from './actions';
import getters from './getters';
import mutations from './mutations';

const defaultState = {
  appLogicData: 'bonjours I am module Logic'
}

const inBrowser = typeof window !== 'undefined';
// if in browser, use pre-fetched state injected by SSR
const state = (inBrowser && window.__INITIAL_STATE__) ? window.__INITIAL_STATE__.page : defaultState;

export default {
  state,
  actions,
  mutations,
  getters
}

在我的 store/app-logic/getters.js

 export default {
  getAppLogicData: state => state.appLogicData
}

应用程序中的任何位置

 computed: {
  ...mapGetters({
   logicData: 'getAppLogicData',
   coucou: 'getHelloThere'
 })
},
mounted () {
  console.log('coucou', this.coucou) --> salut I am module api
  console.log('logicData', this.logicData) --> bonjours I am module Logic
}

奖励积分

如果您想在模块之间进行通信,例如应用程序逻辑中的操作会触发 api 逻辑中的某些内容。所以app-logic(模块一)到api-logic(模块二)

当您指定 root: true 时,它将开始查看商店的根目录。

store/app-logic/actions.js

   callPokemonFromAppLogic: ({ dispatch }, id) => {
    dispatch('callThePokemonFromApiLogic', id, {root:true});
  },

store/api-logic/actions.js

   callThePokemonFromApiLogic: ({ commit }, id) => {

    console.log('I make the call here')
    axios.get('http://pokeapi.salestock.net/api/v2/pokemon/' + id).then(response => commit('update_pokemon', response.data))
  },

store/api-logic/index.js 添加另一个条目

import actions from './actions';
import getters from './getters';
import mutations from './mutations';

const defaultState = {
  appLogicData: 'bonjours I am module Logic',
  pokemon: {}
}

const inBrowser = typeof window !== 'undefined';
// if in browser, use pre-fetched state injected by SSR
const state = (inBrowser && window.__INITIAL_STATE__) ? window.__INITIAL_STATE__.page : defaultState;

export default {
  state,
  actions,
  mutations,
  getters
}

store/api-logic/mutations.js 添加口袋妖怪突变 :p

   update_pokemon: (state, pokemon) => {
    state.pokemon = pokemon
  }

应用程序中的任何位置:

 computed: {
  ...mapGetters({
    bidule: 'bidule',
    pokemon: 'getPokemon'
  })
},
mounted() {
  console.log('bidule', this.bidule)
  this.callPokemonFromAppLogic('1') --> the call
  console.log('the pokemon', this.pokemon.name) --> 'bulbasaur'
},
methods: {
  ...mapActions({
    callPokemonFromAppLogic: 'callPokemonFromAppLogic'
  }),
}

最后你的 Vue devTool 应该是这样的:) Vue devTool 截图商店

瞧,我希望这很清楚。代码示例:

https://github.com/CMarzin/nuxt-vuex-modules

原文由 CMarzin 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 nuxt 版本 2.14^ 中,您不必在商店根 index.js 文件中创建它。

 import Vuex from 'vuex';
import apiModule from './modules/api-logic';
import appModule from './modules/app-logic';

const createStore = () => {
  return new Vuex.Store({
    namespaced: true,
    modules: {
      appLogic: appModule,
      api: apiModule
    }
  });
};

export default createStore

但相反,您可以将根 index.js 文件保留为默认文件或执行您需要的操作。无需导入。

store/index.js

 export const state = () => ({
  counter: 0
})

export const mutations = {
  increment(state) {
    state.counter++
  }
}

export const actions = {
   async nuxtServerInit({ state, commit }, { req }) {
   const cookies = this.$cookies.getAll()
   ...
}

这看起来很简单。

文件夹结构

📦store
 ┣ 📂auth
 ┣ 📂utils
 ┣ 📂posts
 ┃ ┗ 📜actions.js
 ┃ ┗ 📜mutations.js
 ┃ ┗ 📜getters.js
 ┃ ┗ 📜index.js
 ┣ index.js

例子

store/posts/index.js 你可以只放置状态函数。您不需要导入动作、吸气剂和突变。

 export const state = () => ({
   comments: []
})

store/posts/actions.js

 const actions = {
  async getPosts({ commit, state }, obj) {
    return new Promise((resolve, reject) => {
       ...
    }
  }
}

export default actions

store/posts/mutations.js

  const mutations = {
    CLEAR_POST_IMAGE_CONTENT: (state) => {
       state.post_image_content = []
    }
 }

 export default mutations

store/posts/getters.js

 const getters = {
    datatest: (state) => state.datatest,
    headlineFeatures: (state) => state.headlineFeatures,
}

export default getters

效果与@CMarzin 的回答相同,但更清晰

原文由 ßiansor Å. Ålmerol 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题