首页 > 解决方案 > 在 NuxtJS 中重用具有不同 Vuex 存储的组件 - 创建动态/多个 VueX 存储实例

问题描述

我的 UI 中有一个 / 组件,它基于可以使用选择器(例如news-type1news-type2)查询的后端显示新闻。

我想添加该组件的第二个实例,它使用完全相同的后端,但允许用户使用一些不同的选择器(例如news-type3news-type4)。UI 有点像仪表板。在组件文件中实现这种区别.vue是没有问题的(只需接受一些道具并有条件地向用户显示内容),但是:

如何重用商店?由于使用相同的后端,因此新卡的商店代码保持完全相同。但是我不能使用相同的 store实例,因为选择器和加载的新闻应该按组件存储,并且不应该在它们之间共享。令人惊讶的是,我无法在 nuxt 中找到任何简单的解决方案。我认为这将是一个常见的用例。

我的用例的 MWE:

/** Vuex store in store/news.js **/

export const state = () => ({
  // per default only news-type1 is selected, but not news-type2. the user can change that in the UI
  currentSelectors: ['news-type1'], 
  news = [] // object array containing the fetched news
});

export const mutations = {
  // some very simple mutations for the stae
  setSelectors (state, data) {
    state.currentSelectors = data;
  },
  setNews (state, data) {
    state.news = data;
  }
}

export const actions = {
  // simplified get and commit function based on the currentSelectors
  async loadNews ({ commit, state }) {
    const news = await this.$axios.$get(`/api/news/${state.currentSelectors.join(',')}`);
    commit('setNews', news);
    // ... truncated error handling 
  },
  // Helper action. In comparison to the mutation with the same name, it also calls the load action
  async setSelectors ({ commit, dispatch }, selectors) {
    commit('setSelectors', selectors);
    dispatch('loadNews');
  },
};

在我的文章news-card.vue中,我只是映射了这两个状态并调用了这两个动作loadNews(初始加载)和setSelectors(在用户更改了要在 UI 中显示的新闻之后)。这在卡的两个实例中应该保持不变,只是应该转到不同的商店实例。

我目前的替代方法是简单地将商店代码复制粘贴到一个新文件中,然后根据传递给我的组件store/news-two.js的道具使用该商店或原始商店。news-card出于显而易见的原因,那将是不好的做法。是否有更复杂的替代方案可以与 nuxt 一起使用?

我发现的所有相关问题都只针对 Vue,而不针对 nuxt vuex 商店:需要多个 Vuex 模块的多个实例用于多个 Vue 实例如何重用应该使用唯一 vuex 商店实例的组件

标签: vue.jsvuejs2nuxt.jsvuex

解决方案


推荐阅读