【发布时间】:2020-07-03 21:07:58
【问题描述】:
我正在使用 vuex 和 vuejs。 我目前有 2 个 vue 实例(我知道这很糟糕但我不能这样做,这不是问题)
Sidebar.js vue 定义:
//VUEX stores
import { dashboardStore } from './../../js/Stores/DefinitionMappingStores/VuexStoreForDashboardPage'
//first vue with initialisation of state
var vmSidebar = new Vue({
el: '#sidebar-content',
store: dashboardStore,
created() {
this.$store.dispatch('search/setMiniWidgets', miniwidgetsfromjson);
},
})
仪表板.js:
import { dashboardStore } from './../../js/Stores/DefinitionMappingStores/VuexStoreForDashboardPage'
//second vue where state is empty (array(0) instead of having 20+ items inside)
var vm = new Vue({
el: '#dashboard-container',
store: dashboardStore,
mounted: function () {
let that = this; //take this reference, pointing to the current Vue instance
let grid = GridStack.init(options, this.$refs["dashboardref"].$el); //initialise gridstack grid (javascript lib)
grid.on('dropped', function (event, previousWidget, newWidget) { //here is a javascript event)
console.log(this); console.log(that); //here this is the dropped div element / that is the vue instance saved before... but it keep the $store variable not following change...
let vueMiniWidgetComponentFromSidebar = that.$store.getters['search/getFilteredMiniWidgetsById'](idFromNewAddedNode); //here the store search is not initialized but in the other vue from sidebar I see it initialized
});
},
})
搜索模块商店:
const searchModule = {
namespaced: true,
state: {
miniWidgets: []
},
getters: {
getFilteredMiniWidgetsById: (state) => (id) => {
if (id == undefined || id == null || id == "") {
return null;
} else {
return state.miniWidgets.find(miniWidget => miniWidget.Id === id)
}
}
},
}
export default searchModule;
VuexStoreForDashboardPage.js:
import searchModule from './../SearchModuleStore.js'
import userTutorialModule from './../UserTutorialModuleStore.js'
//VUEX stores
export const dashboardStore = new Vuex.Store({
modules: {
//a lot of others modules
search: searchModule,
},
})
我认为我的问题是我保存了 Vue 实例的“状态”,而不是对它的引用,所以每次调用我的 grid.on 函数时,指向保存的 Vue 实例的“那个”引用将是一样的(得救的)。
所以我的问题是:如何让我的 grid.on 函数获得正确的 vue 实例并更改关联的商店?以及如何在这两个文件中让相同的 Vuex 存储共享信息?
编辑:当我使用 Vue 开发工具进行检查时,在组件选项卡中,在我的第二个 vue 实例中,我的 miniWidgets 数组为空,而我的第一个 vue 实例已正确填充。如果我要去 VueX 选项卡,我会看到状态对象正确填充...为什么我的第二个 vue 实例中的 vuex 存储是错误的?
Edit 2 当 2 个 vue 实例在同一个文件中时它可以工作,但当它们在 2 个不同的文件中然后导入到一个文件中时则不能。除了保留这 2 个文件,您知道如何纠正吗?
【问题讨论】:
-
您的存储在 2 个 Vue 实例之间共享 - 如果您从其中一个实例更改状态,另一个实例也将看到更改的状态。如果你想拥有 2 个独立的 Vuex 商店 - 那么你应该使用工厂函数 (stackoverflow.com/a/55273915/5962802)
-
我希望 2 个 vue 实例更改同一个商店。但是现在,我的第二个商店是空的(就像它刚刚使用默认商店值初始化一样),并且与我的第一个 vue 实例更新相比没有改变。如果我像那样导入和导出我的商店,我通常会共享 vuex 商店吗?
-
是的,您正在导出一个 CONST - 因此它将在 2 个 Vue 实例之间共享。
-
但是为什么我在第二个 vue 实例中的第二个 this.$store 没有更新呢?我也尝试像
export const dashboardStore = () => { return new Vuex.Store({ ...})}一样导出 vuex 实例,但它的作用相同 -
如果您能提供一个最小的 CodePen 会有所帮助,以便我们重现您的案例。
标签: javascript vue.js vuex vuex-modules