vue.js - 在 NuxtJS 中重用具有不同 Vuex 存储的组件 - 创建动态/多个 VueX 存储实例
问题描述
我的 UI 中有一个vue.js / nuxt.js组件,它基于可以使用选择器(例如news-type1
,news-type2
)查询的后端显示新闻。
我想添加该组件的第二个实例,它使用完全相同的后端,但允许用户使用一些不同的选择器(例如news-type3
,news-type4
)。UI 有点像仪表板。在组件文件中实现这种区别.vue
是没有问题的(只需接受一些道具并有条件地向用户显示内容),但是:
如何重用vuex商店?由于使用相同的后端,因此新卡的商店代码保持完全相同。但是我不能使用相同的 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 商店实例的组件。
解决方案
推荐阅读
- kubernetes - Affinity - 在 Kubernetes 中每个节点只运行 x 个 pod?
- cordova - Google 在 Ionic 4 中登录得到错误代码 10
- c# - 使用 Azure Redis 在逻辑应用中进行缓存
- c# - 阅读 coinbase api 时无法在 newtonsoft.Json.LinqJvalue 上获取子值?
- python - pyspark sql查询等效函数
- laravel - 如何使用动态路径名路由域子文件夹?
- swift - SwiftUI:导航到视图而不获取后退按钮
- node.js - 续集钩子不触发
- r - R中glm(y~x, family=poisson(link=log))的residuals(XX)和XX$residuals的区别
- reactjs - 无法从反应挂钩状态中获取值